def set_icon(self, *images):
        # Careful!  XChangeProperty takes an array of long when data type
        # is 32-bit (but long can be 64 bit!), so pad high bytes of format if
        # necessary.

        import sys
        format = {
            ('little', 4): 'BGRA',
            ('little', 8): 'BGRAAAAA',
            ('big', 4):    'ARGB',
            ('big', 8):    'AAAAARGB'
        }[(sys.byteorder, sizeof(c_ulong))]

        data = asbytes('')
        for image in images:
            image = image.get_image_data()
            pitch = -(image.width * len(format))
            s = c_buffer(sizeof(c_ulong) * 2)
            memmove(s, cast((c_ulong * 2)(image.width, image.height), 
                            POINTER(c_ubyte)), len(s))
            data += s.raw + image.get_data(format, pitch)
        buffer = (c_ubyte * len(data))()
        memmove(buffer, data, len(data))
        atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_ICON'), False)
        xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL,
            32, xlib.PropModeReplace, buffer, len(data)//sizeof(c_ulong))
Beispiel #2
0
    def set_icon(self, *images):
        # Careful!  XChangeProperty takes an array of long when data type
        # is 32-bit (but long can be 64 bit!), so pad high bytes of format if
        # necessary.

        import sys
        format = {
            ('little', 4): 'BGRA',
            ('little', 8): 'BGRAAAAA',
            ('big', 4): 'ARGB',
            ('big', 8): 'AAAAARGB'
        }[(sys.byteorder, sizeof(c_ulong))]

        data = asbytes('')
        for image in images:
            image = image.get_image_data()
            pitch = -(image.width * len(format))
            s = c_buffer(sizeof(c_ulong) * 2)
            memmove(
                s,
                cast((c_ulong * 2)(image.width, image.height),
                     POINTER(c_ubyte)), len(s))
            data += s.raw + image.get_data(format, pitch)
        buffer = (c_ubyte * len(data))()
        memmove(buffer, data, len(data))
        atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_ICON'),
                                False)
        xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL,
                             32, xlib.PropModeReplace, buffer,
                             len(data) // sizeof(c_ulong))
    def _set_wm_state(self, *states):
        # Set property
        net_wm_state = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_STATE'), False)
        atoms = []
        for state in states:
            atoms.append(xlib.XInternAtom(self._x_display, asbytes(state), False))
        atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False)
        if len(atoms):
            atoms_ar = (xlib.Atom * len(atoms))(*atoms)
            xlib.XChangeProperty(self._x_display, self._window,
                net_wm_state, atom_type, 32, xlib.PropModePrepend,
                cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms))
        else:
            xlib.XDeleteProperty(self._x_display, self._window, net_wm_state)

        # Nudge the WM
        e = xlib.XEvent()
        e.xclient.type = xlib.ClientMessage
        e.xclient.message_type = net_wm_state
        e.xclient.display = cast(self._x_display, POINTER(xlib.Display))
        e.xclient.window = self._window
        e.xclient.format = 32
        e.xclient.data.l[0] = xlib.PropModePrepend
        for i, atom in enumerate(atoms):
            e.xclient.data.l[i + 1] = atom
        xlib.XSendEvent(self._x_display, self._get_root(),
            False, xlib.SubstructureRedirectMask, byref(e))
Beispiel #4
0
    def _set_wm_state(self, *states):
        # Set property
        net_wm_state = xlib.XInternAtom(self._x_display,
                                        asbytes('_NET_WM_STATE'), False)
        atoms = []
        for state in states:
            atoms.append(
                xlib.XInternAtom(self._x_display, asbytes(state), False))
        atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False)
        if len(atoms):
            atoms_ar = (xlib.Atom * len(atoms))(*atoms)
            xlib.XChangeProperty(self._x_display, self._window, net_wm_state,
                                 atom_type, 32, xlib.PropModePrepend,
                                 cast(pointer(atoms_ar), POINTER(c_ubyte)),
                                 len(atoms))
        else:
            xlib.XDeleteProperty(self._x_display, self._window, net_wm_state)

        # Nudge the WM
        e = xlib.XEvent()
        e.xclient.type = xlib.ClientMessage
        e.xclient.message_type = net_wm_state
        e.xclient.display = cast(self._x_display, POINTER(xlib.Display))
        e.xclient.window = self._window
        e.xclient.format = 32
        e.xclient.data.l[0] = xlib.PropModePrepend
        for i, atom in enumerate(atoms):
            e.xclient.data.l[i + 1] = atom
        xlib.XSendEvent(self._x_display, self._get_root(), False,
                        xlib.SubstructureRedirectMask, byref(e))
Beispiel #5
0
 def _event_clientmessage(self, ev):
     atom = ev.xclient.data.l[0]
     if atom == xlib.XInternAtom(ev.xclient.display,
                                 asbytes('WM_DELETE_WINDOW'), False):
         self.dispatch_event('on_close')
     elif (self._enable_xsync and atom == xlib.XInternAtom(
             ev.xclient.display, asbytes('_NET_WM_SYNC_REQUEST'), False)):
         lo = ev.xclient.data.l[2]
         hi = ev.xclient.data.l[3]
         self._current_sync_value = xsync.XSyncValue(hi, lo)
Beispiel #6
0
 def _event_clientmessage(self, ev):
     atom = ev.xclient.data.l[0]
     if atom == xlib.XInternAtom(ev.xclient.display, asbytes("WM_DELETE_WINDOW"), False):
         self.dispatch_event("on_close")
     elif self._enable_xsync and atom == xlib.XInternAtom(
         ev.xclient.display, asbytes("_NET_WM_SYNC_REQUEST"), False
     ):
         lo = ev.xclient.data.l[2]
         hi = ev.xclient.data.l[3]
         self._current_sync_value = xsync.XSyncValue(hi, lo)
Beispiel #7
0
def ffmpeg_file_info(file):
    """Get information on the file:

        - number of streams
        - duration
        - artist
        - album
        - date
        - track

    :rtype: FileInfo
    :return: The file info instance containing all the meta information.
    """
    info = FileInfo()
    info.n_streams = file.context.contents.nb_streams
    info.start_time = file.context.contents.start_time
    info.duration = file.context.contents.duration

    entry = avutil.av_dict_get(file.context.contents.metadata, asbytes('title'), None, 0)
    if entry:
        info.title = asstr(entry.contents.value)

    entry = avutil.av_dict_get(file.context.contents.metadata,
                               asbytes('artist'),
                               None,
                               0) \
            or \
            avutil.av_dict_get(file.context.contents.metadata,
                               asbytes('album_artist'),
                               None,
                               0)
    if entry:
        info.author = asstr(entry.contents.value)

    entry = avutil.av_dict_get(file.context.contents.metadata, asbytes('copyright'), None, 0)
    if entry:
        info.copyright = asstr(entry.contents.value)

    entry = avutil.av_dict_get(file.context.contents.metadata, asbytes('comment'), None, 0)
    if entry:
        info.comment = asstr(entry.contents.value)

    entry = avutil.av_dict_get(file.context.contents.metadata, asbytes('album'), None, 0)
    if entry:
        info.album = asstr(entry.contents.value)

    entry = avutil.av_dict_get(file.context.contents.metadata, asbytes('date'), None, 0)
    if entry:
        info.year = int(entry.contents.value)

    entry = avutil.av_dict_get(file.context.contents.metadata, asbytes('track'), None, 0)
    if entry:
        info.track = asstr(entry.contents.value)

    entry = avutil.av_dict_get(file.context.contents.metadata, asbytes('genre'), None, 0)
    if entry:
        info.genre = asstr(entry.contents.value)

    return info
Beispiel #8
0
 def _set_atoms_property(self, name, values, mode=xlib.PropModeReplace):
     name_atom = xlib.XInternAtom(self._x_display, asbytes(name), False)
     atoms = []
     for value in values:
         atoms.append(xlib.XInternAtom(self._x_display, asbytes(value), False))
     atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False)
     if len(atoms):
         atoms_ar = (xlib.Atom * len(atoms))(*atoms)
         xlib.XChangeProperty(self._x_display, self._window,
             name_atom, atom_type, 32, mode,
             cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms))
     else:
         xlib.XDeleteProperty(self._x_display, self._window, net_wm_state)
 def _set_atoms_property(self, name, values, mode=xlib.PropModeReplace):
     name_atom = xlib.XInternAtom(self._x_display, asbytes(name), False)
     atoms = []
     for value in values:
         atoms.append(xlib.XInternAtom(self._x_display, asbytes(value), False))
     atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False)
     if len(atoms):
         atoms_ar = (xlib.Atom * len(atoms))(*atoms)
         xlib.XChangeProperty(self._x_display, self._window,
             name_atom, atom_type, 32, mode,
             cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms))
     else:
         xlib.XDeleteProperty(self._x_display, self._window, net_wm_state)
Beispiel #10
0
class WaveForm(RIFFForm):
    _chunk_types = {
        asbytes('fmt '): WaveFormatChunk,
        asbytes('data'): WaveDataChunk
    }

    def get_format_chunk(self):
        for chunk in self.get_chunks():
            if isinstance(chunk, WaveFormatChunk):
                return chunk

    def get_data_chunk(self):
        for chunk in self.get_chunks():
            if isinstance(chunk, WaveDataChunk):
                return chunk
Beispiel #11
0
 def write_chunk(self, outfile, tag, data):
     """
     Write a PNG chunk to the output file, including length and checksum.
     """
     # http://www.w3.org/TR/PNG/#5Chunk-layout
     tag = asbytes(tag)
     data = asbytes(data)
     outfile.write(struct.pack("!I", len(data)))
     outfile.write(tag)
     outfile.write(data)
     checksum = zlib.crc32(tag)
     checksum = zlib.crc32(data, checksum)
     # <ah> Avoid DeprecationWarning: struct integer overflow masking
     #      with Python2.5/Windows.
     checksum = checksum & 0xffffffff
     outfile.write(struct.pack("!I", checksum))
Beispiel #12
0
 def write_chunk(self, outfile, tag, data):
     """
     Write a PNG chunk to the output file, including length and checksum.
     """
     # http://www.w3.org/TR/PNG/#5Chunk-layout
     tag = asbytes(tag)
     data = asbytes(data)
     outfile.write(struct.pack("!I", len(data)))
     outfile.write(tag)
     outfile.write(data)
     checksum = zlib.crc32(tag)
     checksum = zlib.crc32(data, checksum)
     # <ah> Avoid DeprecationWarning: struct integer overflow masking
     #      with Python2.5/Windows.
     checksum = checksum & 0xffffffff
     outfile.write(struct.pack("!I", checksum))
Beispiel #13
0
 def _load_font_face_from_file(file_name):
     font_face = FT_Face()
     ft_library = ft_get_library()
     error = FT_New_Face(ft_library, asbytes(file_name), 0,
                         byref(font_face))
     FreeTypeError.check_and_raise_on_error(
         'Could not load font from "%s"' % file_name, error)
     return font_face
Beispiel #14
0
 def from_file(cls, file_name):
     ft_library = ft_get_library()
     ft_face = FT_Face()
     FT_New_Face(ft_library,
                 asbytes(file_name),
                 0,
                 byref(ft_face))
     return cls(ft_face)
Beispiel #15
0
 def from_file(cls, file_name):
     ft_library = ft_get_library()
     ft_face = FT_Face()
     FT_New_Face(ft_library,
                 asbytes(file_name),
                 0,
                 byref(ft_face))
     return cls(ft_face)
Beispiel #16
0
    def __init__(self, *args, **kwargs):
        super(RIFFType, self).__init__(*args, **kwargs)

        self.file.seek(self.offset)
        form = self.file.read(4)
        if form != asbytes('WAVE'):
            raise RIFFFormatException('Unsupported RIFF form "%s"' % form)

        self.form = WaveForm(self.file, self.offset + 4)
Beispiel #17
0
    def __init__(self, *args, **kwargs):
        super(RIFFType, self).__init__(*args, **kwargs)

        self.file.seek(self.offset)
        form = self.file.read(4)
        if form != asbytes('WAVE'):
            raise RIFFFormatException('Unsupported RIFF form "%s"' % form)

        self.form = WaveForm(self.file, self.offset + 4)
Beispiel #18
0
def _install_restore_mode_child():
    global _mode_write_pipe
    global _restore_mode_child_installed

    if _restore_mode_child_installed:
        return

    # Parent communicates to child by sending "mode packets" through a pipe:
    mode_read_pipe, _mode_write_pipe = os.pipe()

    if os.fork() == 0:
        # Child process (watches for parent to die then restores video mode(s).
        os.close(_mode_write_pipe)

        # Set up SIGHUP to be the signal for when the parent dies.
        PR_SET_PDEATHSIG = 1
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
        libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong,
                               ctypes.c_ulong, ctypes.c_ulong)
        libc.prctl(PR_SET_PDEATHSIG, signal.SIGHUP, 0, 0, 0)

        # SIGHUP indicates the parent has died.  The child lock is unlocked, it
        # stops reading from the mode packet pipe and restores video modes on
        # all displays/screens it knows about.
        def _sighup(signum, frame):
            parent_wait_lock.release()

        parent_wait_lock = threading.Lock()
        parent_wait_lock.acquire()
        signal.signal(signal.SIGHUP, _sighup)

        # Wait for parent to die and read packets from parent pipe
        packets = []
        buffer = asbytes('')
        while parent_wait_lock.locked():
            try:
                data = os.read(mode_read_pipe, ModePacket.size)
                buffer += data
                # Decode packets
                while len(buffer) >= ModePacket.size:
                    packet = ModePacket.decode(buffer[:ModePacket.size])
                    packets.append(packet)
                    buffer = buffer[ModePacket.size:]
            except OSError:
                pass  # Interrupted system call

        for packet in packets:
            packet.set()
        os._exit(0)

    else:
        # Parent process.  Clean up pipe then continue running program as
        # normal.  Send mode packets through pipe as additional
        # displays/screens are mode switched.
        os.close(mode_read_pipe)
        _restore_mode_child_installed = True
def _install_restore_mode_child():
    global _mode_write_pipe
    global _restore_mode_child_installed

    if _restore_mode_child_installed:
        return

    # Parent communicates to child by sending "mode packets" through a pipe:
    mode_read_pipe, _mode_write_pipe = os.pipe()

    if os.fork() == 0:
        # Child process (watches for parent to die then restores video mode(s).
        os.close(_mode_write_pipe)

        # Set up SIGHUP to be the signal for when the parent dies.
        PR_SET_PDEATHSIG = 1
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
        libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong,
                               ctypes.c_ulong, ctypes.c_ulong)
        libc.prctl(PR_SET_PDEATHSIG, signal.SIGHUP, 0, 0, 0)

        # SIGHUP indicates the parent has died.  The child lock is unlocked, it
        # stops reading from the mode packet pipe and restores video modes on
        # all displays/screens it knows about.
        def _sighup(signum, frame):
            parent_wait_lock.release();
        parent_wait_lock = threading.Lock();
        parent_wait_lock.acquire()
        signal.signal(signal.SIGHUP, _sighup)

        # Wait for parent to die and read packets from parent pipe
        packets = []
        buffer = asbytes('')
        while parent_wait_lock.locked():
            try:
                data = os.read(mode_read_pipe, ModePacket.size)
                buffer += data
                # Decode packets
                while len(buffer) >= ModePacket.size:
                    packet = ModePacket.decode(buffer[:ModePacket.size])
                    packets.append(packet)
                    buffer = buffer[ModePacket.size:]
            except OSError:
                pass # Interrupted system call

        for packet in packets:
            packet.set()
        os._exit(0)
        
    else:
        # Parent process.  Clean up pipe then continue running program as
        # normal.  Send mode packets through pipe as additional
        # displays/screens are mode switched.
        os.close(mode_read_pipe)
        _restore_mode_child_installed = True
Beispiel #20
0
    def _set_string(self, name, value):
        assert self._pattern
        assert name
        assert self._fontconfig

        if not value:
            return

        value = value.encode('utf8')

        self._fontconfig.FcPatternAddString(self._pattern, name, asbytes(value))
Beispiel #21
0
    def _set_string(self, name, value):
        assert self._pattern
        assert name
        assert self._fontconfig

        if not value:
            return

        value = value.encode('utf8')

        self._fontconfig.FcPatternAddString(self._pattern, name, asbytes(value))
Beispiel #22
0
 def resolve(self):
     from pyglet.gl import current_context
     if not current_context:
         raise Exception('Call to function "%s" before GL context created' %
                         self.name)
     address = wglGetProcAddress(asbytes(self.name))
     if cast(address, POINTER(c_int)):  # check cast because address is func
         self.func = cast(address, self.ftype)
         decorate_function(self.func, self.name)
     else:
         self.func = missing_function(self.name, self.requires,
                                      self.suggestions)
Beispiel #23
0
 def resolve(self):
     from pyglet.gl import current_context
     if not current_context:
         raise Exception(
             'Call to function "%s" before GL context created' % self.name)
     address = wglGetProcAddress(asbytes(self.name))
     if cast(address, POINTER(c_int)):  # check cast because address is func
         self.func = cast(address, self.ftype)
         decorate_function(self.func, self.name)
     else:
         self.func = missing_function(
             self.name, self.requires, self.suggestions)
Beispiel #24
0
class RIFFFile(RIFFForm):
    _chunk_types = {
        asbytes('RIFF'): RIFFType,
    }

    def __init__(self, file):
        if not hasattr(file, 'seek'):
            file = BytesIO(file.read())

        super(RIFFFile, self).__init__(file, 0)

    def get_wave_form(self):
        chunks = self.get_chunks()
        if len(chunks) == 1 and isinstance(chunks[0], RIFFType):
            return chunks[0].form
Beispiel #25
0
    def __call__(self, *args, **kwargs):
        from pyglet.gl import current_context
        if not current_context:
            raise Exception('Call to function "%s" before GL context created' %
                            self.name)
        address = wglGetProcAddress(asbytes(self.name))
        if cast(address, POINTER(c_int)):  # check cast because address is func
            self.func = cast(address, self.ftype)
            decorate_function(self.func, self.name)
        else:
            self.func = missing_function(self.name, self.requires,
                                         self.suggestions)

        self.__class__ = makeWGLFunction(self.func)

        return self.func(*args, **kwargs)
Beispiel #26
0
    def __call__(self, *args, **kwargs):
        if self.func:
            return self.func(*args, **kwargs)

        from pyglet.gl import current_context

        if not current_context:
            raise Exception('Call to function "%s" before GL context created' % self.name)
        address = wglGetProcAddress(asbytes(self.name))
        if cast(address, POINTER(c_int)):  # check cast because address is func
            self.func = cast(address, self.ftype)
            decorate_function(self.func, self.name)
        else:
            self.func = missing_function(self.name, self.requires, self.suggestions)
        result = self.func(*args, **kwargs)
        return result
Beispiel #27
0
    def get_logfont(name, size, bold, italic, dpi):
        # Create a dummy DC for coordinate mapping
        dc = user32.GetDC(0)
        if dpi is None:
            dpi = 96
        logpixelsy = dpi

        logfont = LOGFONT()
        # Conversion of point size to device pixels
        logfont.lfHeight = int(-size * logpixelsy // 72)
        if bold:
            logfont.lfWeight = FW_BOLD
        else:
            logfont.lfWeight = FW_NORMAL
        logfont.lfItalic = italic
        logfont.lfFaceName = asbytes(name)
        logfont.lfQuality = ANTIALIASED_QUALITY
        return logfont
Beispiel #28
0
    def get_logfont(name, size, bold, italic, dpi):
        # Create a dummy DC for coordinate mapping
        dc = user32.GetDC(0)
        if dpi is None:
            dpi = 96
        logpixelsy = dpi

        logfont = LOGFONT()
        # Conversion of point size to device pixels
        logfont.lfHeight = int(-size * logpixelsy // 72)
        if bold:
            logfont.lfWeight = FW_BOLD
        else:
            logfont.lfWeight = FW_NORMAL
        logfont.lfItalic = italic
        logfont.lfFaceName = asbytes(name)
        logfont.lfQuality = ANTIALIASED_QUALITY
        return logfont
def link_GL(name, restype, argtypes, requires=None, suggestions=None):
    try:
        func = getattr(gl_lib, name)
        func.restype = restype
        func.argtypes = argtypes
        decorate_function(func, name)
        return func
    except AttributeError:
        if _have_getprocaddress:
            # Fallback if implemented but not in ABI
            bname = cast(pointer(create_string_buffer(asbytes(name))), POINTER(c_ubyte))
            addr = glXGetProcAddressARB(bname)
            if addr:
                ftype = CFUNCTYPE(*((restype,) + tuple(argtypes)))
                func = cast(addr, ftype)
                decorate_function(func, name)
                return func

    return missing_function(name, requires, suggestions)
Beispiel #30
0
 def _set_text_property(self, name, value, allow_utf8=True):
     atom = xlib.XInternAtom(self._x_display, asbytes(name), False)
     if not atom:
         raise XlibException('Undefined atom "%s"' % name)
     assert type(value) in (str, unicode)
     property = xlib.XTextProperty()
     if _have_utf8 and allow_utf8:
         buf = create_string_buffer(value.encode("utf8"))
         result = xlib.Xutf8TextListToTextProperty(
             self._x_display, cast(pointer(buf), c_char_p), 1, xlib.XUTF8StringStyle, byref(property)
         )
         if result < 0:
             raise XlibException("Could not create UTF8 text property")
     else:
         buf = create_string_buffer(value.encode("ascii", "ignore"))
         result = xlib.XStringListToTextProperty(cast(pointer(buf), c_char_p), 1, byref(property))
         if result < 0:
             raise XlibException("Could not create text property")
     xlib.XSetTextProperty(self._x_display, self._window, byref(property), atom)
Beispiel #31
0
 def _set_text_property(self, name, value, allow_utf8=True):
     atom = xlib.XInternAtom(self._x_display, asbytes(name), False)
     if not atom:
         raise XlibException('Undefined atom "%s"' % name)
     assert type(value) in (str, unicode)
     property = xlib.XTextProperty()
     if _have_utf8 and allow_utf8:
         buf = create_string_buffer(value.encode('utf8'))
         result = xlib.Xutf8TextListToTextProperty(self._x_display,
             cast(pointer(buf), c_char_p), 1, xlib.XUTF8StringStyle, 
             byref(property))
         if result < 0:
             raise XlibException('Could not create UTF8 text property')
     else:
         buf = create_string_buffer(value.encode('ascii', 'ignore'))
         result = xlib.XStringListToTextProperty(
             cast(pointer(buf), c_char_p), 1, byref(property))
         if result < 0:
             raise XlibException('Could not create text property')
     xlib.XSetTextProperty(self._x_display,
         self._window, byref(property), atom)
Beispiel #32
0
 def check_file(self, path, file, result):
     loader = resource.Loader(path, script_home=self.script_home)
     self.assertTrue(loader.file(file).read() == asbytes('%s\n' % result))
Beispiel #33
0
__version__ = '$Id$'

from collections import OrderedDict
from ctypes import *

import pyglet.lib
from pyglet.compat import asbytes, asstr
from pyglet.font.base import FontException

# fontconfig library definitions

(FcResultMatch, FcResultNoMatch, FcResultTypeMismatch, FcResultNoId,
 FcResultOutOfMemory) = range(5)
FcResult = c_int

FC_FAMILY = asbytes('family')
FC_SIZE = asbytes('size')
FC_SLANT = asbytes('slant')
FC_WEIGHT = asbytes('weight')
FC_FT_FACE = asbytes('ftface')
FC_FILE = asbytes('file')

FC_WEIGHT_REGULAR = 80
FC_WEIGHT_BOLD = 200

FC_SLANT_ROMAN = 0
FC_SLANT_ITALIC = 100

(FcTypeVoid, FcTypeInteger, FcTypeDouble, FcTypeString, FcTypeBool,
 FcTypeMatrix, FcTypeCharSet, FcTypeFTFace, FcTypeLangSet) = range(9)
FcType = c_int
def test_zipfile_trailing_slash(loader):
    loader.path = ['dir1/res.zip/']
    assert loader.file('f7.txt').read() == asbytes('%s\n' % 'F7')
Beispiel #35
0
    def read(self):
        """
        Read a simple PNG file, return width, height, pixels and image metadata

        This function is a very early prototype with limited flexibility
        and excessive use of memory.
        """
        signature = self.file.read(8)
        if (signature != struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)):
            raise Error("PNG file has invalid header")
        compressed = []
        image_metadata = {}
        while True:
            try:
                tag, data = self.read_chunk()
            except ValueError as e:
                raise Error('Chunk error: ' + e.args[0])

            # print >> sys.stderr, tag, len(data)
            if tag == asbytes('IHDR'): # http://www.w3.org/TR/PNG/#11IHDR
                (width, height, bits_per_sample, color_type,
                 compression_method, filter_method,
                 interlaced) = struct.unpack("!2I5B", data)
                bps = bits_per_sample // 8
                if bps == 0:
                    raise Error("unsupported pixel depth")
                if bps > 2 or bits_per_sample != (bps * 8):
                    raise Error("invalid pixel depth")
                if color_type == 0:
                    greyscale = True
                    has_alpha = False
                    has_palette = False
                    planes = 1
                elif color_type == 2:
                    greyscale = False
                    has_alpha = False
                    has_palette = False
                    planes = 3
                elif color_type == 3:
                    greyscale = False
                    has_alpha = False
                    has_palette = True
                    planes = 1
                elif color_type == 4:
                    greyscale = True
                    has_alpha = True
                    has_palette = False
                    planes = 2
                elif color_type == 6:
                    greyscale = False
                    has_alpha = True
                    has_palette = False
                    planes = 4
                else:
                    raise Error("unknown PNG colour type %s" % color_type)
                if compression_method != 0:
                    raise Error("unknown compression method")
                if filter_method != 0:
                    raise Error("unknown filter method")
                self.bps = bps
                self.planes = planes
                self.psize = bps * planes
                self.width = width
                self.height = height
                self.row_bytes = width * self.psize
            elif tag == asbytes('IDAT'): # http://www.w3.org/TR/PNG/#11IDAT
                compressed.append(data)
            elif tag == asbytes('bKGD'):
                if greyscale:
                    image_metadata["background"] = struct.unpack("!1H", data)
                elif has_palette:
                    image_metadata["background"] = struct.unpack("!1B", data)
                else:
                    image_metadata["background"] = struct.unpack("!3H", data)
            elif tag == asbytes('tRNS'):
                if greyscale:
                    image_metadata["transparent"] = struct.unpack("!1H", data)
                elif has_palette:
                    # may have several transparent colors
                    image_metadata["transparent"] = array('B', data)
                else:
                    image_metadata["transparent"] = struct.unpack("!3H", data)
            elif tag == asbytes('gAMA'):
                image_metadata["gamma"] = (
                    struct.unpack("!L", data)[0]) / 100000.0
            elif tag == asbytes('PLTE'): # http://www.w3.org/TR/PNG/#11PLTE
                if not len(data) or len(data) % 3 != 0 or len(data) > 3*(2**(self.bps*8)):
                    raise Error("invalid palette size")
                image_metadata["palette"] = array('B', data)
            elif tag == asbytes('IEND'): # http://www.w3.org/TR/PNG/#11IEND
                break
        scanlines = array('B', zlib.decompress(asbytes('').join(compressed)))
        if interlaced:
            pixels = self.deinterlace(scanlines)
        else:
            pixels = self.read_flat(scanlines)

        if has_palette:
            if "palette" in image_metadata:
                # convert the indexed data to RGB, or RGBA if transparent
                rgb_pixels = array('B')
                for pixel in pixels:
                    pal_index = pixel*3
                    rgb_pixels.extend(image_metadata["palette"][pal_index:pal_index+3])
                    # if there are transparent colors, use RGBA
                    if "transparent" in image_metadata:
                        if pixel in image_metadata["transparent"]:
                            rgb_pixels.append(0)
                        else:
                            rgb_pixels.append(255)
                pixels = rgb_pixels
                self.planes = 3

                if "transparent" in image_metadata:
                    self.planes += 1
                    has_alpha = True
                    del image_metadata["transparent"]

                if "background" in image_metadata:
                    pal_index = image_metadata["background"][0]*3
                    image_metadata["background"] = \
                            image_metadata["palette"][pal_index:pal_index+3]
            else:
                raise Error("color_type is indexed but no palette was found")

        image_metadata["greyscale"] = greyscale
        image_metadata["has_alpha"] = has_alpha
        image_metadata["bytes_per_sample"] = bps
        image_metadata["interlaced"] = interlaced
        return width, height, pixels, image_metadata
def test_zipfile_subdirs(loader):
    loader.path = ['dir1/res.zip/dir1', 'dir1/res.zip/dir1/dir1/']
    assert loader.file('f8.txt').read() == asbytes('%s\n' % 'F8')
    assert loader.file('f9.txt').read() == asbytes('%s\n' % 'F9')
Beispiel #37
0
    def read(self):
        """
        Read a simple PNG file, return width, height, pixels and image metadata

        This function is a very early prototype with limited flexibility
        and excessive use of memory.
        """
        signature = self.file.read(8)
        if (signature != struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)):
            raise Error("PNG file has invalid header")
        compressed = []
        image_metadata = {}
        while True:
            try:
                tag, data = self.read_chunk()
            except ValueError, e:
                raise Error('Chunk error: ' + e.args[0])

            # print >> sys.stderr, tag, len(data)
            if tag == asbytes('IHDR'): # http://www.w3.org/TR/PNG/#11IHDR
                (width, height, bits_per_sample, color_type,
                 compression_method, filter_method,
                 interlaced) = struct.unpack("!2I5B", data)
                bps = bits_per_sample // 8
                if bps == 0:
                    raise Error("unsupported pixel depth")
                if bps > 2 or bits_per_sample != (bps * 8):
                    raise Error("invalid pixel depth")
                if color_type == 0:
                    greyscale = True
                    has_alpha = False
                    has_palette = False
                    planes = 1
                elif color_type == 2:
                    greyscale = False
                    has_alpha = False
                    has_palette = False
                    planes = 3
                elif color_type == 3:
                    greyscale = False
                    has_alpha = False
                    has_palette = True
                    planes = 1
                elif color_type == 4:
                    greyscale = True
                    has_alpha = True
                    has_palette = False
                    planes = 2
                elif color_type == 6:
                    greyscale = False
                    has_alpha = True
                    has_palette = False
                    planes = 4
                else:
                    raise Error("unknown PNG colour type %s" % color_type)
                if compression_method != 0:
                    raise Error("unknown compression method")
                if filter_method != 0:
                    raise Error("unknown filter method")
                self.bps = bps
                self.planes = planes
                self.psize = bps * planes
                self.width = width
                self.height = height
                self.row_bytes = width * self.psize
            elif tag == asbytes('IDAT'): # http://www.w3.org/TR/PNG/#11IDAT
                compressed.append(data)
            elif tag == asbytes('bKGD'):
                if greyscale:
                    image_metadata["background"] = struct.unpack("!1H", data)
                elif has_palette:
                    image_metadata["background"] = struct.unpack("!1B", data)
                else:
                    image_metadata["background"] = struct.unpack("!3H", data)
            elif tag == asbytes('tRNS'):
                if greyscale:
                    image_metadata["transparent"] = struct.unpack("!1H", data)
                elif has_palette:
                    # may have several transparent colors
                    image_metadata["transparent"] = array('B', data)
                else:
                    image_metadata["transparent"] = struct.unpack("!3H", data)
            elif tag == asbytes('gAMA'):
                image_metadata["gamma"] = (
                    struct.unpack("!L", data)[0]) / 100000.0
            elif tag == asbytes('PLTE'): # http://www.w3.org/TR/PNG/#11PLTE
                if not len(data) or len(data) % 3 != 0 or len(data) > 3*(2**(self.bps*8)):
                    raise Error("invalid palette size")
                image_metadata["palette"] = array('B', data)
            elif tag == asbytes('IEND'): # http://www.w3.org/TR/PNG/#11IEND
                break
Beispiel #38
0
class Reader:
    """
    PNG decoder in pure Python.
    """
    def __init__(self, _guess=None, **kw):
        """
        Create a PNG decoder object.

        The constructor expects exactly one keyword argument. If you
        supply a positional argument instead, it will guess the input
        type. You can choose among the following arguments:
        filename - name of PNG input file
        file - object with a read() method
        pixels - array or string with PNG data

        """
        if ((_guess is not None and len(kw) != 0)
                or (_guess is None and len(kw) != 1)):
            raise TypeError("Reader() takes exactly 1 argument")

        if _guess is not None:
            if isinstance(_guess, array):
                kw["pixels"] = _guess
            elif isinstance(_guess, str):
                kw["filename"] = _guess
            elif isinstance(_guess, file):
                kw["file"] = _guess

        if "filename" in kw:
            self.file = file(kw["filename"])
        elif "file" in kw:
            self.file = kw["file"]
        elif "pixels" in kw:
            self.file = _readable(kw["pixels"])
        else:
            raise TypeError("expecting filename, file or pixels array")

    def read_chunk(self):
        """
        Read a PNG chunk from the input file, return tag name and data.
        """
        # http://www.w3.org/TR/PNG/#5Chunk-layout
        try:
            data_bytes, tag = struct.unpack('!I4s', self.file.read(8))
        except struct.error:
            raise ValueError('Chunk too short for header')
        data = self.file.read(data_bytes)
        if len(data) != data_bytes:
            raise ValueError('Chunk %s too short for required %i data octets' %
                             (tag, data_bytes))
        checksum = self.file.read(4)
        if len(checksum) != 4:
            raise ValueError('Chunk %s too short for checksum', tag)
        verify = zlib.crc32(tag)
        verify = zlib.crc32(data, verify)
        # Whether the output from zlib.crc32 is signed or not varies
        # according to hideous implementation details, see
        # http://bugs.python.org/issue1202 .
        # We coerce it to be positive here (in a way which works on
        # Python 2.3 and older).
        verify &= 2**32 - 1
        verify = struct.pack('!I', verify)
        if checksum != verify:
            # print repr(checksum)
            (a, ) = struct.unpack('!I', checksum)
            (b, ) = struct.unpack('!I', verify)
            raise ValueError("Checksum error in %s chunk: 0x%X != 0x%X" %
                             (tag, a, b))
        return tag, data

    def _reconstruct_sub(self, offset, xstep, ystep):
        """
        Reverse sub filter.
        """
        pixels = self.pixels
        a_offset = offset
        offset += self.psize * xstep
        if xstep == 1:
            for index in range(self.psize, self.row_bytes):
                x = pixels[offset]
                a = pixels[a_offset]
                pixels[offset] = (x + a) & 0xff
                offset += 1
                a_offset += 1
        else:
            byte_step = self.psize * xstep
            for index in range(byte_step, self.row_bytes, byte_step):
                for i in range(self.psize):
                    x = pixels[offset + i]
                    a = pixels[a_offset + i]
                    pixels[offset + i] = (x + a) & 0xff
                offset += self.psize * xstep
                a_offset += self.psize * xstep

    def _reconstruct_up(self, offset, xstep, ystep):
        """
        Reverse up filter.
        """
        pixels = self.pixels
        b_offset = offset - (self.row_bytes * ystep)
        if xstep == 1:
            for index in range(self.row_bytes):
                x = pixels[offset]
                b = pixels[b_offset]
                pixels[offset] = (x + b) & 0xff
                offset += 1
                b_offset += 1
        else:
            for index in range(0, self.row_bytes, xstep * self.psize):
                for i in range(self.psize):
                    x = pixels[offset + i]
                    b = pixels[b_offset + i]
                    pixels[offset + i] = (x + b) & 0xff
                offset += self.psize * xstep
                b_offset += self.psize * xstep

    def _reconstruct_average(self, offset, xstep, ystep):
        """
        Reverse average filter.
        """
        pixels = self.pixels
        a_offset = offset - (self.psize * xstep)
        b_offset = offset - (self.row_bytes * ystep)
        if xstep == 1:
            for index in range(self.row_bytes):
                x = pixels[offset]
                if index < self.psize:
                    a = 0
                else:
                    a = pixels[a_offset]
                if b_offset < 0:
                    b = 0
                else:
                    b = pixels[b_offset]
                pixels[offset] = (x + ((a + b) >> 1)) & 0xff
                offset += 1
                a_offset += 1
                b_offset += 1
        else:
            for index in range(0, self.row_bytes, self.psize * xstep):
                for i in range(self.psize):
                    x = pixels[offset + i]
                    if index < self.psize:
                        a = 0
                    else:
                        a = pixels[a_offset + i]
                    if b_offset < 0:
                        b = 0
                    else:
                        b = pixels[b_offset + i]
                    pixels[offset + i] = (x + ((a + b) >> 1)) & 0xff
                offset += self.psize * xstep
                a_offset += self.psize * xstep
                b_offset += self.psize * xstep

    def _reconstruct_paeth(self, offset, xstep, ystep):
        """
        Reverse Paeth filter.
        """
        pixels = self.pixels
        a_offset = offset - (self.psize * xstep)
        b_offset = offset - (self.row_bytes * ystep)
        c_offset = b_offset - (self.psize * xstep)
        # There's enough inside this loop that it's probably not worth
        # optimising for xstep == 1
        for index in range(0, self.row_bytes, self.psize * xstep):
            for i in range(self.psize):
                x = pixels[offset + i]
                if index < self.psize:
                    a = c = 0
                    b = pixels[b_offset + i]
                else:
                    a = pixels[a_offset + i]
                    b = pixels[b_offset + i]
                    c = pixels[c_offset + i]
                p = a + b - c
                pa = abs(p - a)
                pb = abs(p - b)
                pc = abs(p - c)
                if pa <= pb and pa <= pc:
                    pr = a
                elif pb <= pc:
                    pr = b
                else:
                    pr = c
                pixels[offset + i] = (x + pr) & 0xff
            offset += self.psize * xstep
            a_offset += self.psize * xstep
            b_offset += self.psize * xstep
            c_offset += self.psize * xstep

    # N.B. PNG files with 'up', 'average' or 'paeth' filters on the
    # first line of a pass are legal. The code above for 'average'
    # deals with this case explicitly. For up we map to the null
    # filter and for paeth we map to the sub filter.

    def reconstruct_line(self, filter_type, first_line, offset, xstep, ystep):
        # print >> sys.stderr, "Filter type %s, first_line=%s" % (
        #                      filter_type, first_line)
        filter_type += (first_line << 8)
        if filter_type == 1 or filter_type == 0x101 or filter_type == 0x104:
            self._reconstruct_sub(offset, xstep, ystep)
        elif filter_type == 2:
            self._reconstruct_up(offset, xstep, ystep)
        elif filter_type == 3 or filter_type == 0x103:
            self._reconstruct_average(offset, xstep, ystep)
        elif filter_type == 4:
            self._reconstruct_paeth(offset, xstep, ystep)
        return

    def deinterlace(self, scanlines):
        # print >> sys.stderr, ("Reading interlaced, w=%s, r=%s, planes=%s," +
        #     " bpp=%s") % (self.width, self.height, self.planes, self.bps)
        a = array('B')
        self.pixels = a
        # Make the array big enough
        temp = scanlines[0:self.width * self.height * self.psize]
        a.extend(temp)
        source_offset = 0
        for xstart, ystart, xstep, ystep in _adam7:
            # print >> sys.stderr, "Adam7: start=%s,%s step=%s,%s" % (
            #     xstart, ystart, xstep, ystep)
            filter_first_line = 1
            for y in range(ystart, self.height, ystep):
                if xstart >= self.width:
                    continue
                filter_type = scanlines[source_offset]
                source_offset += 1
                if xstep == 1:
                    offset = y * self.row_bytes
                    a[offset:offset+self.row_bytes] = \
                        scanlines[source_offset:source_offset + self.row_bytes]
                    source_offset += self.row_bytes
                else:
                    # Note we want the ceiling of (width - xstart) / xtep
                    row_len = self.psize * (
                        (self.width - xstart + xstep - 1) / xstep)
                    offset = y * self.row_bytes + xstart * self.psize
                    end_offset = (y + 1) * self.row_bytes
                    skip = self.psize * xstep
                    for i in range(self.psize):
                        a[offset+i:end_offset:skip] = \
                            scanlines[source_offset + i:
                                      source_offset + row_len:
                                      self.psize]
                    source_offset += row_len
                if filter_type:
                    self.reconstruct_line(filter_type, filter_first_line,
                                          offset, xstep, ystep)
                filter_first_line = 0
        return a

    def read_flat(self, scanlines):
        a = array('B')
        self.pixels = a
        offset = 0
        source_offset = 0
        filter_first_line = 1
        for y in range(self.height):
            filter_type = scanlines[source_offset]
            source_offset += 1
            a.extend(scanlines[source_offset:source_offset + self.row_bytes])
            if filter_type:
                self.reconstruct_line(filter_type, filter_first_line, offset,
                                      1, 1)
            filter_first_line = 0
            offset += self.row_bytes
            source_offset += self.row_bytes
        return a

    def read(self):
        """
        Read a simple PNG file, return width, height, pixels and image metadata

        This function is a very early prototype with limited flexibility
        and excessive use of memory.
        """
        signature = self.file.read(8)
        if (signature != struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)):
            raise Error("PNG file has invalid header")
        compressed = []
        image_metadata = {}
        while True:
            try:
                tag, data = self.read_chunk()
            except ValueError, e:
                raise Error('Chunk error: ' + e.args[0])

            # print >> sys.stderr, tag, len(data)
            if tag == asbytes('IHDR'):  # http://www.w3.org/TR/PNG/#11IHDR
                (width, height, bits_per_sample, color_type,
                 compression_method, filter_method,
                 interlaced) = struct.unpack("!2I5B", data)
                bps = bits_per_sample // 8
                if bps == 0:
                    raise Error("unsupported pixel depth")
                if bps > 2 or bits_per_sample != (bps * 8):
                    raise Error("invalid pixel depth")
                if color_type == 0:
                    greyscale = True
                    has_alpha = False
                    has_palette = False
                    planes = 1
                elif color_type == 2:
                    greyscale = False
                    has_alpha = False
                    has_palette = False
                    planes = 3
                elif color_type == 3:
                    greyscale = False
                    has_alpha = False
                    has_palette = True
                    planes = 1
                elif color_type == 4:
                    greyscale = True
                    has_alpha = True
                    has_palette = False
                    planes = 2
                elif color_type == 6:
                    greyscale = False
                    has_alpha = True
                    has_palette = False
                    planes = 4
                else:
                    raise Error("unknown PNG colour type %s" % color_type)
                if compression_method != 0:
                    raise Error("unknown compression method")
                if filter_method != 0:
                    raise Error("unknown filter method")
                self.bps = bps
                self.planes = planes
                self.psize = bps * planes
                self.width = width
                self.height = height
                self.row_bytes = width * self.psize
            elif tag == asbytes('IDAT'):  # http://www.w3.org/TR/PNG/#11IDAT
                compressed.append(data)
            elif tag == asbytes('bKGD'):
                if greyscale:
                    image_metadata["background"] = struct.unpack("!1H", data)
                elif has_palette:
                    image_metadata["background"] = struct.unpack("!1B", data)
                else:
                    image_metadata["background"] = struct.unpack("!3H", data)
            elif tag == asbytes('tRNS'):
                if greyscale:
                    image_metadata["transparent"] = struct.unpack("!1H", data)
                elif has_palette:
                    # may have several transparent colors
                    image_metadata["transparent"] = array('B', data)
                else:
                    image_metadata["transparent"] = struct.unpack("!3H", data)
            elif tag == asbytes('gAMA'):
                image_metadata["gamma"] = (struct.unpack("!L",
                                                         data)[0]) / 100000.0
            elif tag == asbytes('PLTE'):  # http://www.w3.org/TR/PNG/#11PLTE
                if not len(data) or len(data) % 3 != 0 or len(
                        data) > 3 * (2**(self.bps * 8)):
                    raise Error("invalid palette size")
                image_metadata["palette"] = array('B', data)
            elif tag == asbytes('IEND'):  # http://www.w3.org/TR/PNG/#11IEND
                break
        scanlines = array('B', zlib.decompress(asbytes('').join(compressed)))
        if interlaced:
            pixels = self.deinterlace(scanlines)
        else:
            pixels = self.read_flat(scanlines)

        if has_palette:
            if "palette" in image_metadata:
                # convert the indexed data to RGB, or RGBA if transparent
                rgb_pixels = array('B')
                for pixel in pixels:
                    pal_index = pixel * 3
                    rgb_pixels.extend(
                        image_metadata["palette"][pal_index:pal_index + 3])
                    # if there are transparent colors, use RGBA
                    if "transparent" in image_metadata:
                        if pixel in image_metadata["transparent"]:
                            rgb_pixels.append(0)
                        else:
                            rgb_pixels.append(255)
                pixels = rgb_pixels
                self.planes = 3

                if "transparent" in image_metadata:
                    self.planes += 1
                    has_alpha = True
                    del image_metadata["transparent"]

                if "background" in image_metadata:
                    pal_index = image_metadata["background"][0] * 3
                    image_metadata["background"] = \
                            image_metadata["palette"][pal_index:pal_index+3]
            else:
                raise Error("color_type is indexed but no palette was found")

        image_metadata["greyscale"] = greyscale
        image_metadata["has_alpha"] = has_alpha
        image_metadata["bytes_per_sample"] = bps
        image_metadata["interlaced"] = interlaced
        return width, height, pixels, image_metadata
Beispiel #39
0
 def check_file(self, path, file, result):
     loader = resource.Loader(path, script_home=self.script_home)
     self.assertTrue(loader.file(file).read() == asbytes('%s\n' % result))
Beispiel #40
0
    def read(self):
        """
        Read a simple PNG file, return width, height, pixels and image metadata

        This function is a very early prototype with limited flexibility
        and excessive use of memory.
        """
        signature = self.file.read(8)
        if (signature != struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)):
            raise Error("PNG file has invalid header")
        compressed = []
        image_metadata = {}
        while True:
            try:
                tag, data = self.read_chunk()
            except ValueError, e:
                raise Error('Chunk error: ' + e.args[0])

            # print >> sys.stderr, tag, len(data)
            if tag == asbytes('IHDR'):  # http://www.w3.org/TR/PNG/#11IHDR
                (width, height, bits_per_sample, color_type,
                 compression_method, filter_method,
                 interlaced) = struct.unpack("!2I5B", data)
                bps = bits_per_sample // 8
                if bps == 0:
                    raise Error("unsupported pixel depth")
                if bps > 2 or bits_per_sample != (bps * 8):
                    raise Error("invalid pixel depth")
                if color_type == 0:
                    greyscale = True
                    has_alpha = False
                    has_palette = False
                    planes = 1
                elif color_type == 2:
                    greyscale = False
                    has_alpha = False
                    has_palette = False
                    planes = 3
                elif color_type == 3:
                    greyscale = False
                    has_alpha = False
                    has_palette = True
                    planes = 1
                elif color_type == 4:
                    greyscale = True
                    has_alpha = True
                    has_palette = False
                    planes = 2
                elif color_type == 6:
                    greyscale = False
                    has_alpha = True
                    has_palette = False
                    planes = 4
                else:
                    raise Error("unknown PNG colour type %s" % color_type)
                if compression_method != 0:
                    raise Error("unknown compression method")
                if filter_method != 0:
                    raise Error("unknown filter method")
                self.bps = bps
                self.planes = planes
                self.psize = bps * planes
                self.width = width
                self.height = height
                self.row_bytes = width * self.psize
            elif tag == asbytes('IDAT'):  # http://www.w3.org/TR/PNG/#11IDAT
                compressed.append(data)
            elif tag == asbytes('bKGD'):
                if greyscale:
                    image_metadata["background"] = struct.unpack("!1H", data)
                elif has_palette:
                    image_metadata["background"] = struct.unpack("!1B", data)
                else:
                    image_metadata["background"] = struct.unpack("!3H", data)
            elif tag == asbytes('tRNS'):
                if greyscale:
                    image_metadata["transparent"] = struct.unpack("!1H", data)
                elif has_palette:
                    # may have several transparent colors
                    image_metadata["transparent"] = array('B', data)
                else:
                    image_metadata["transparent"] = struct.unpack("!3H", data)
            elif tag == asbytes('gAMA'):
                image_metadata["gamma"] = (struct.unpack("!L",
                                                         data)[0]) / 100000.0
            elif tag == asbytes('PLTE'):  # http://www.w3.org/TR/PNG/#11PLTE
                if not len(data) or len(data) % 3 != 0 or len(
                        data) > 3 * (2**(self.bps * 8)):
                    raise Error("invalid palette size")
                image_metadata["palette"] = array('B', data)
            elif tag == asbytes('IEND'):  # http://www.w3.org/TR/PNG/#11IEND
                break
 def decode(cls, data):
     display, screen, width, height, rate = \
         struct.unpack(cls.format, data)
     return cls(display.strip(asbytes('\0')), screen, width, height, rate)
Beispiel #42
0
if __name__ == '__main__':
    op = optparse.OptionParser()
    op.add_option('-d', '--device', dest='device',
                  help='use device DEVICE', metavar='DEVICE')
    (options, args) = op.parse_args(sys.argv[1:])

    default_device = ctypes.cast(
        alc.alcGetString(None, alc.ALC_DEFAULT_DEVICE_SPECIFIER), ctypes.c_char_p).value
    capture_default_device = ctypes.cast(
        alc.alcGetString(None, alc.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER), ctypes.c_char_p).value

    print('Default device:         %s' % default_device)
    print('Default capture device: %s' % capture_default_device)

    if alc.alcIsExtensionPresent(None, ctypes.create_string_buffer(b'ALC_ENUMERATION_EXT')):
        devices = split_nul_strings(alc.alcGetString(None, alc.ALC_DEVICE_SPECIFIER))
        capture_devices = split_nul_strings(alc.alcGetString(None, alc.ALC_CAPTURE_DEVICE_SPECIFIER))

        print('Devices:                %s' % b', '.join(devices))
        print('Capture devices:        %s\n' % b', '.join(capture_devices))

    if options.device:
        print('Using device "%s"...' % options.device)
        driver = openal.create_audio_driver(asbytes(options.device))
    else:
        print('Using default device...')
        driver = openal.create_audio_driver()

    print('OpenAL version %d.%d' % driver.get_version())
    print('Extensions:              %s' % ', '.join(driver.get_extensions()))
Beispiel #43
0
 def _load_font_face_from_file(file_name):
     font_face = FT_Face()
     ft_library = ft_get_library()
     error = FT_New_Face(ft_library, asbytes(file_name), 0, byref(font_face))
     FreeTypeError.check_and_raise_on_error('Could not load font from "%s"' % file_name, error)
     return font_face
Beispiel #44
0
 def set(self):
     self._event.set()
     os.write(self._sync_file_write, asbytes('1'))
Beispiel #45
0
            return self._video_packets[0].timestamp

    def get_next_video_frame(self):
        if not self.video_format:
            return

        if self._ensure_video_packets():
            packet = self._video_packets.pop(0)
            if _debug:
                print 'Waiting for', packet

            # Block until decoding is complete
            self._condition.acquire()
            while packet.image == 0:
                self._condition.wait()
            self._condition.release()

            if _debug:
                print 'Returning', packet
            return packet.image

av.avbin_init()
if pyglet.options['debug_media']:
    _debug = True
    av.avbin_set_log_level(AVBIN_LOG_DEBUG)
else:
    _debug = False
    av.avbin_set_log_level(AVBIN_LOG_QUIET)

_have_frame_rate = av.avbin_have_feature(asbytes('frame_rate'))
Beispiel #46
0
 def set(self):
     self._event.set()
     os.write(self._sync_file_write, asbytes('1'))
Beispiel #47
0
 def decode(cls, data):
     display, screen, width, height, rate = \
         struct.unpack(cls.format, data)
     return cls(display.strip(asbytes('\0')), screen, width, height, rate)
    def _create(self):
        # Unmap existing window if necessary while we fiddle with it.
        if self._window and self._mapped:
            self._unmap()

        self._x_display = self.display._display
        self._x_screen_id = self.display.x_screen


        # Create X window if not already existing.
        if not self._window:
            root = xlib.XRootWindow(self._x_display, self._x_screen_id)

            visual_info = self.config.get_visual_info()

            visual = visual_info.visual
            visual_id = xlib.XVisualIDFromVisual(visual)
            default_visual = xlib.XDefaultVisual(
                self._x_display, self._x_screen_id)
            default_visual_id = xlib.XVisualIDFromVisual(default_visual)
            window_attributes = xlib.XSetWindowAttributes()
            if visual_id != default_visual_id:
                window_attributes.colormap = xlib.XCreateColormap(
                    self._x_display, root, visual, xlib.AllocNone)
            else:
                window_attributes.colormap = xlib.XDefaultColormap(
                    self._x_display, self._x_screen_id)
            window_attributes.bit_gravity = xlib.StaticGravity

            # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration
            #            unless CWBackPixel is given in mask.  Should have
            #            no effect on other systems, so it's set
            #            unconditionally.
            mask = xlib.CWColormap | xlib.CWBitGravity | xlib.CWBackPixel

            if self._fullscreen:
                width, height = self.screen.width, self.screen.height
                self._view_x = (width - self._width) // 2
                self._view_y = (height - self._height) // 2
            else:
                width, height = self._width, self._height
                self._view_x = self._view_y = 0

            self._window = xlib.XCreateWindow(self._x_display, root,
                0, 0, width, height, 0, visual_info.depth,
                xlib.InputOutput, visual, mask,
                byref(window_attributes))
            self._view = xlib.XCreateWindow(self._x_display, 
                self._window, self._view_x, self._view_y, 
                self._width, self._height, 0, visual_info.depth, 
                xlib.InputOutput, visual, mask, 
                byref(window_attributes));
            xlib.XMapWindow(self._x_display, self._view)
            xlib.XSelectInput(
                self._x_display, self._view, self._default_event_mask)

            self.display._window_map[self._window] = \
                self.dispatch_platform_event
            self.display._window_map[self._view] = \
                self.dispatch_platform_event_view

            self.canvas = XlibCanvas(self.display, self._view)

            self.context.attach(self.canvas)
            self.context.set_vsync(self._vsync) # XXX ?

            # Setting null background pixmap disables drawing the background,
            # preventing flicker while resizing (in theory).
            #
            # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration if
            #            this is called.  As it doesn't seem to have any
            #            effect anyway, it's just commented out.
            #xlib.XSetWindowBackgroundPixmap(self._x_display, self._window, 0)

            self._enable_xsync = (pyglet.options['xsync'] and
                                  self.display._enable_xsync and
                                  self.config.double_buffer)

            # Set supported protocols
            protocols = []
            protocols.append(xlib.XInternAtom(self._x_display,
                                              asbytes('WM_DELETE_WINDOW'), False))
            if self._enable_xsync:
                protocols.append(xlib.XInternAtom(self._x_display,
                                                  asbytes('_NET_WM_SYNC_REQUEST'),
                                                  False))
            protocols = (c_ulong * len(protocols))(*protocols)
            xlib.XSetWMProtocols(self._x_display, self._window,
                                 protocols, len(protocols))

            # Create window resize sync counter
            if self._enable_xsync:
                value = xsync.XSyncValue()
                self._sync_counter = xlib.XID(
                    xsync.XSyncCreateCounter(self._x_display, value))
                atom = xlib.XInternAtom(self._x_display,
                                        asbytes('_NET_WM_SYNC_REQUEST_COUNTER'), False)
                ptr = pointer(self._sync_counter)

                xlib.XChangeProperty(self._x_display, self._window,
                                     atom, XA_CARDINAL, 32,
                                     xlib.PropModeReplace,
                                     cast(ptr, POINTER(c_ubyte)), 1)
        # Set window attributes
        attributes = xlib.XSetWindowAttributes()
        attributes_mask = 0

        self._override_redirect = False
        if self._fullscreen:
            if pyglet.options['xlib_fullscreen_override_redirect']:
                # Try not to use this any more, it causes problems; disabled
                # by default in favour of _NET_WM_STATE_FULLSCREEN.
                attributes.override_redirect = self._fullscreen
                attributes_mask |= xlib.CWOverrideRedirect
                self._override_redirect = True
            else:
                self._set_wm_state('_NET_WM_STATE_FULLSCREEN')

        if self._fullscreen:
            xlib.XMoveResizeWindow(self._x_display, self._window, 
                self.screen.x, self.screen.y, 
                self.screen.width, self.screen.height)
        else:
            xlib.XResizeWindow(self._x_display, self._window, 
                self._width, self._height)

        xlib.XChangeWindowAttributes(self._x_display, self._window, 
            attributes_mask, byref(attributes))

        # Set style
        styles = {
            self.WINDOW_STYLE_DEFAULT: '_NET_WM_WINDOW_TYPE_NORMAL',
            self.WINDOW_STYLE_DIALOG: '_NET_WM_WINDOW_TYPE_DIALOG',
            self.WINDOW_STYLE_TOOL: '_NET_WM_WINDOW_TYPE_UTILITY',
        }
        if self._style in styles:
            self._set_atoms_property('_NET_WM_WINDOW_TYPE', 
                                     (styles[self._style],))
        elif self._style == self.WINDOW_STYLE_BORDERLESS:
            MWM_HINTS_DECORATIONS = 1 << 1
            PROP_MWM_HINTS_ELEMENTS = 5
            mwmhints = mwmhints_t()
            mwmhints.flags = MWM_HINTS_DECORATIONS
            mwmhints.decorations = 0
            name = xlib.XInternAtom(self._x_display, asbytes('_MOTIF_WM_HINTS'), False)
            xlib.XChangeProperty(self._x_display, self._window,
                name, name, 32, xlib.PropModeReplace, 
                cast(pointer(mwmhints), POINTER(c_ubyte)),
                PROP_MWM_HINTS_ELEMENTS)

        # Set resizeable
        if not self._resizable and not self._fullscreen:
            self.set_minimum_size(self._width, self._height)
            self.set_maximum_size(self._width, self._height)

        # Set caption
        self.set_caption(self._caption)

        # Create input context.  A good but very outdated reference for this
        # is http://www.sbin.org/doc/Xlib/chapt_11.html
        if _have_utf8 and not self._x_ic:
            if not self.display._x_im:
                xlib.XSetLocaleModifiers(asbytes('@im=none'))
                self.display._x_im = \
                    xlib.XOpenIM(self._x_display, None, None, None)

            xlib.XFlush(self._x_display);

            # Need to set argtypes on this function because it's vararg,
            # and ctypes guesses wrong.
            xlib.XCreateIC.argtypes = [xlib.XIM,    
                                       c_char_p, c_int,
                                       c_char_p, xlib.Window,
                                       c_char_p, xlib.Window,
                                       c_void_p]
            self._x_ic = xlib.XCreateIC(self.display._x_im, 
                asbytes('inputStyle'), xlib.XIMPreeditNothing|xlib.XIMStatusNothing,
                asbytes('clientWindow'), self._window,
                asbytes('focusWindow'), self._window,
                None)

            filter_events = c_ulong()
            xlib.XGetICValues(self._x_ic,
                              'filterEvents', byref(filter_events),
                              None)
            self._default_event_mask |= filter_events.value
            xlib.XSetICFocus(self._x_ic)

        self.switch_to()
        if self._visible:
            self.set_visible(True)

        self.set_mouse_platform_visible()
        self._applied_mouse_exclusive = None
        self._update_exclusivity()
Beispiel #49
0
    def get_next_video_frame(self):
        if not self.video_format:
            return

        if self._ensure_video_packets():
            packet = self._video_packets.pop(0)
            if _debug:
                print("Waiting for", packet)

            # Block until decoding is complete
            self._condition.acquire()
            while packet.image == 0:
                self._condition.wait()
            self._condition.release()

            if _debug:
                print("Returning", packet)
            return packet.image


av.avbin_init()
if pyglet.options["debug_media"]:
    _debug = True
    av.avbin_set_log_level(AVBIN_LOG_DEBUG)
else:
    _debug = False
    av.avbin_set_log_level(AVBIN_LOG_QUIET)

_have_frame_rate = av.avbin_have_feature(asbytes("frame_rate"))
Beispiel #50
0
fontconfig.FcPatternCreate.restype = c_void_p
fontconfig.FcFontMatch.restype = c_void_p
fontconfig.FcFreeTypeCharIndex.restype = c_uint

fontconfig.FcPatternAddDouble.argtypes = [c_void_p, c_char_p, c_double]
fontconfig.FcPatternAddInteger.argtypes = [c_void_p, c_char_p, c_int]
fontconfig.FcPatternAddString.argtypes = [c_void_p, c_char_p, c_char_p]
fontconfig.FcConfigSubstitute.argtypes = [c_void_p, c_void_p, c_int]
fontconfig.FcDefaultSubstitute.argtypes = [c_void_p]
fontconfig.FcFontMatch.argtypes = [c_void_p, c_void_p, c_void_p]
fontconfig.FcPatternDestroy.argtypes = [c_void_p]

fontconfig.FcPatternGetFTFace.argtypes = [c_void_p, c_char_p, c_int, c_void_p]
fontconfig.FcPatternGet.argtypes = [c_void_p, c_char_p, c_int, c_void_p]

FC_FAMILY = asbytes('family')
FC_SIZE = asbytes('size')
FC_SLANT = asbytes('slant')
FC_WEIGHT = asbytes('weight')
FC_FT_FACE = asbytes('ftface')
FC_FILE = asbytes('file')

FC_WEIGHT_REGULAR = 80
FC_WEIGHT_BOLD = 200

FC_SLANT_ROMAN = 0
FC_SLANT_ITALIC = 100

FT_STYLE_FLAG_ITALIC = 1
FT_STYLE_FLAG_BOLD = 2
Beispiel #51
0
            return self._video_packets[0].timestamp

    def get_next_video_frame(self):
        if not self.video_format:
            return

        if self._ensure_video_packets():
            packet = self._video_packets.pop(0)
            if _debug:
                print 'Waiting for', packet

            # Block until decoding is complete
            self._condition.acquire()
            while packet.image == 0:
                self._condition.wait()
            self._condition.release()

            if _debug:
                print 'Returning', packet
            return packet.image

av.avbin_init()
if pyglet.options['debug_media']:
    _debug = True
    av.avbin_set_log_level(AVBIN_LOG_DEBUG)
else:
    _debug = False
    av.avbin_set_log_level(AVBIN_LOG_QUIET)

_have_frame_rate = av.avbin_have_feature(asbytes('frame_rate'))
Beispiel #52
0
    def _create(self):
        # Unmap existing window if necessary while we fiddle with it.
        if self._window and self._mapped:
            self._unmap()

        self._x_display = self.display._display
        self._x_screen_id = self.display.x_screen


        # Create X window if not already existing.
        if not self._window:
            root = xlib.XRootWindow(self._x_display, self._x_screen_id)

            visual_info = self.config.get_visual_info()

            visual = visual_info.visual
            visual_id = xlib.XVisualIDFromVisual(visual)
            default_visual = xlib.XDefaultVisual(
                self._x_display, self._x_screen_id)
            default_visual_id = xlib.XVisualIDFromVisual(default_visual)
            window_attributes = xlib.XSetWindowAttributes()
            if visual_id != default_visual_id:
                window_attributes.colormap = xlib.XCreateColormap(
                    self._x_display, root, visual, xlib.AllocNone)
            else:
                window_attributes.colormap = xlib.XDefaultColormap(
                    self._x_display, self._x_screen_id)
            window_attributes.bit_gravity = xlib.StaticGravity

            # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration
            #            unless CWBackPixel is given in mask.  Should have
            #            no effect on other systems, so it's set
            #            unconditionally.
            mask = xlib.CWColormap | xlib.CWBitGravity | xlib.CWBackPixel

            if self._fullscreen:
                width, height = self.screen.width, self.screen.height
                self._view_x = (width - self._width) // 2
                self._view_y = (height - self._height) // 2
            else:
                width, height = self._width, self._height
                self._view_x = self._view_y = 0

            self._window = xlib.XCreateWindow(self._x_display, root,
                0, 0, width, height, 0, visual_info.depth,
                xlib.InputOutput, visual, mask,
                byref(window_attributes))
            self._view = xlib.XCreateWindow(self._x_display, 
                self._window, self._view_x, self._view_y, 
                self._width, self._height, 0, visual_info.depth, 
                xlib.InputOutput, visual, mask, 
                byref(window_attributes));
            xlib.XMapWindow(self._x_display, self._view)
            xlib.XSelectInput(
                self._x_display, self._view, self._default_event_mask)

            self.display._window_map[self._window] = \
                self.dispatch_platform_event
            self.display._window_map[self._view] = \
                self.dispatch_platform_event_view

            self.canvas = XlibCanvas(self.display, self._view)

            self.context.attach(self.canvas)
            self.context.set_vsync(self._vsync) # XXX ?

            # Setting null background pixmap disables drawing the background,
            # preventing flicker while resizing (in theory).
            #
            # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration if
            #            this is called.  As it doesn't seem to have any
            #            effect anyway, it's just commented out.
            #xlib.XSetWindowBackgroundPixmap(self._x_display, self._window, 0)

            self._enable_xsync = (pyglet.options['xsync'] and
                                  self.display._enable_xsync and
                                  self.config.double_buffer)

            # Set supported protocols
            protocols = []
            protocols.append(xlib.XInternAtom(self._x_display,
                                              asbytes('WM_DELETE_WINDOW'), False))
            if self._enable_xsync:
                protocols.append(xlib.XInternAtom(self._x_display,
                                                  asbytes('_NET_WM_SYNC_REQUEST'),
                                                  False))
            protocols = (c_ulong * len(protocols))(*protocols)
            xlib.XSetWMProtocols(self._x_display, self._window,
                                 protocols, len(protocols))

            # Create window resize sync counter
            if self._enable_xsync:
                value = xsync.XSyncValue()
                self._sync_counter = xlib.XID(
                    xsync.XSyncCreateCounter(self._x_display, value))
                atom = xlib.XInternAtom(self._x_display,
                                        asbytes('_NET_WM_SYNC_REQUEST_COUNTER'), False)
                ptr = pointer(self._sync_counter)

                xlib.XChangeProperty(self._x_display, self._window,
                                     atom, XA_CARDINAL, 32,
                                     xlib.PropModeReplace,
                                     cast(ptr, POINTER(c_ubyte)), 1)
        # Set window attributes
        attributes = xlib.XSetWindowAttributes()
        attributes_mask = 0

        self._override_redirect = False
        if self._fullscreen:
            if pyglet.options['xlib_fullscreen_override_redirect']:
                # Try not to use this any more, it causes problems; disabled
                # by default in favour of _NET_WM_STATE_FULLSCREEN.
                attributes.override_redirect = self._fullscreen
                attributes_mask |= xlib.CWOverrideRedirect
                self._override_redirect = True
            else:
                self._set_wm_state('_NET_WM_STATE_FULLSCREEN')

        if self._fullscreen:
            xlib.XMoveResizeWindow(self._x_display, self._window, 
                self.screen.x, self.screen.y, 
                self.screen.width, self.screen.height)
        else:
            xlib.XResizeWindow(self._x_display, self._window, 
                self._width, self._height)

        xlib.XChangeWindowAttributes(self._x_display, self._window, 
            attributes_mask, byref(attributes))

        # Set style
        styles = {
            self.WINDOW_STYLE_DEFAULT: '_NET_WM_WINDOW_TYPE_NORMAL',
            self.WINDOW_STYLE_DIALOG: '_NET_WM_WINDOW_TYPE_DIALOG',
            self.WINDOW_STYLE_TOOL: '_NET_WM_WINDOW_TYPE_UTILITY',
        }
        if self._style in styles:
            self._set_atoms_property('_NET_WM_WINDOW_TYPE', 
                                     (styles[self._style],))
        elif self._style == self.WINDOW_STYLE_BORDERLESS:
            MWM_HINTS_DECORATIONS = 1 << 1
            PROP_MWM_HINTS_ELEMENTS = 5
            mwmhints = mwmhints_t()
            mwmhints.flags = MWM_HINTS_DECORATIONS
            mwmhints.decorations = 0
            name = xlib.XInternAtom(self._x_display, '_MOTIF_WM_HINTS', False)
            xlib.XChangeProperty(self._x_display, self._window,
                name, name, 32, xlib.PropModeReplace, 
                cast(pointer(mwmhints), POINTER(c_ubyte)),
                PROP_MWM_HINTS_ELEMENTS)

        # Set resizeable
        if not self._resizable and not self._fullscreen:
            self.set_minimum_size(self._width, self._height)
            self.set_maximum_size(self._width, self._height)

        # Set caption
        self.set_caption(self._caption)

        # Create input context.  A good but very outdated reference for this
        # is http://www.sbin.org/doc/Xlib/chapt_11.html
        if _have_utf8 and not self._x_ic:
            if not self.display._x_im:
                xlib.XSetLocaleModifiers(asbytes('@im=none'))
                self.display._x_im = \
                    xlib.XOpenIM(self._x_display, None, None, None)

            xlib.XFlush(self._x_display);

            # Need to set argtypes on this function because it's vararg,
            # and ctypes guesses wrong.
            xlib.XCreateIC.argtypes = [xlib.XIM,    
                                       c_char_p, c_int,
                                       c_char_p, xlib.Window,
                                       c_char_p, xlib.Window,
                                       c_void_p]
            self._x_ic = xlib.XCreateIC(self.display._x_im, 
                asbytes('inputStyle'), xlib.XIMPreeditNothing|xlib.XIMStatusNothing,
                asbytes('clientWindow'), self._window,
                asbytes('focusWindow'), self._window,
                None)

            filter_events = c_ulong()
            xlib.XGetICValues(self._x_ic,
                              'filterEvents', byref(filter_events),
                              None)
            self._default_event_mask |= filter_events.value
            xlib.XSetICFocus(self._x_ic)

        self.switch_to()
        if self._visible:
            self.set_visible(True)

        self.set_mouse_platform_visible()
        self._applied_mouse_exclusive = None
        self._update_exclusivity()