Ejemplo n.º 1
0
Archivo: loader.py Proyecto: bernt/pymt
    def _load_urllib(self, filename):
        '''(internal) Loading a network file. First download it, save it to a
        temporary file, and pass it to _load_local()'''
        import urllib2, tempfile
        data = None
        try:
            suffix = '.%s'  % (filename.split('.')[-1])
            _out_osfd, _out_filename = tempfile.mkstemp(
                    prefix='pymtloader', suffix=suffix)

            # read from internet
            fd = urllib2.urlopen(filename)
            idata = fd.read()
            fd.close()

            # write to local filename
            os.write(_out_osfd, idata)
            os.close(_out_osfd)

            # load data
            data = self._load_local(_out_filename)
        except:
            pymt_logger.exception('Failed to load image <%s>' % filename)
            return self.error_image
        finally:
            os.unlink(_out_filename)

        return data
Ejemplo n.º 2
0
    def _load_urllib(self, filename):
        '''(internal) Loading a network file. First download it, save it to a
        temporary file, and pass it to _load_local()'''
        import urllib2, tempfile
        data = None
        try:
            suffix = '.%s'  % (filename.split('.')[-1])
            _out_osfd, _out_filename = tempfile.mkstemp(
                    prefix='pymtloader', suffix=suffix)

            # read from internet
            fd = urllib2.urlopen(filename)
            idata = fd.read()
            fd.close()

            # write to local filename
            os.write(_out_osfd, idata)
            os.close(_out_osfd)

            # load data
            data = self._load_local(_out_filename)
        except Exception:
            pymt_logger.exception('Failed to load image <%s>' % filename)
            return self.error_image
        finally:
            os.unlink(_out_filename)

        return data
Ejemplo n.º 3
0
def parse_color(c, default=None):
    if not c:
        return default
    if c == 'none':
        return None
    if c[0] == '#': c = c[1:]
    if c.startswith('url(#'):
        return c[5:-1]
    try:
        if str(c) in colormap:
            c = colormap[str(c)][1:]
            r = int(c[0:2], 16)
            g = int(c[2:4], 16)
            b = int(c[4:6], 16)
        elif len(c) == 6:
            r = int(c[0:2], 16)
            g = int(c[2:4], 16)
            b = int(c[4:6], 16)
        elif len(c) == 3:
            r = int(c[0], 16) * 17
            g = int(c[1], 16) * 17
            b = int(c[2], 16) * 17
        else:
            pymt_logger.exception('Squirtle: incorrect length for color %s' % str(c))
        return [r,g,b,255]
    except Exception, ex:
        pymt_logger.exception('Squirtle: exception parsing color %s' % str(c))
        return None
Ejemplo n.º 4
0
    def _load_urllib(self, filename):
        """(internal) Loading a network file. First download it, save it to a
        temporary file, and pass it to _load_local()"""
        import urllib2, tempfile

        data = None
        try:
            suffix = ".%s" % (filename.split(".")[-1])
            _out_osfd, _out_filename = tempfile.mkstemp(prefix="pymtloader", suffix=suffix)

            # read from internet
            fd = urllib2.urlopen(filename)
            idata = fd.read()
            fd.close()

            # write to local filename
            fd = open(_out_filename, "wb")
            fd.write(idata)
            fd.close()

            # load data
            data = self._load_local(_out_filename)
        except:
            pymt_logger.exception("Failed to load image <%s>" % filename)
            return self.error_image
        finally:
            os.unlink(_out_filename)

        return data
Ejemplo n.º 5
0
    def createNode(self, node):
        from xml.dom import Node
        factory = MTWidgetFactory.get
        if node.nodeType == Node.ELEMENT_NODE:
            class_name = node.nodeName

            # parameters
            k = {}
            widget_id = None
            for name, value in node.attributes.items():
                if str(name) == 'id':
                    widget_id = eval(value)
                else:
                    k[str(name)] = eval(value)

            # create widget
            try:
                nodeWidget = factory(class_name)(**k)
                if widget_id is not None:
                    self.registerdb[widget_id] = nodeWidget
            except:
                pymt_logger.exception('XMLWidget: unable to create widget %s' \
                                      % class_name)
                raise

            # add child widgets
            for c in node.childNodes:
                w = self.createNode(c)
                if w:
                    nodeWidget.add_widget(w)

            return nodeWidget
Ejemplo n.º 6
0
def parse_color(c, default=None):
    if not c:
        return default
    if c == 'none':
        return None
    if c[0] == '#': c = c[1:]
    if c.startswith('url(#'):
        return c[5:-1]
    try:
        if str(c) in colormap:
            c = colormap[str(c)][1:]
            r = int(c[0:2], 16)
            g = int(c[2:4], 16)
            b = int(c[4:6], 16)
        elif len(c) == 6:
            r = int(c[0:2], 16)
            g = int(c[2:4], 16)
            b = int(c[4:6], 16)
        elif len(c) == 3:
            r = int(c[0], 16) * 17
            g = int(c[1], 16) * 17
            b = int(c[2], 16) * 17
        else:
            pymt_logger.exception('Squirtle: incorrect length for color %s' %
                                  str(c))
        return [r, g, b, 255]
    except Exception, ex:
        pymt_logger.exception('Squirtle: exception parsing color %s' % str(c))
        return None
Ejemplo n.º 7
0
    def run(self):
        self.haveSocket = False
        # create socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # fix trouble if python leave without cleaning well the socket
        # not needed under windows, he can reuse addr even if the socket
        # are in fin2 or wait state.
        if os.name in ['posix', 'mac'] and hasattr(socket, 'SO_REUSEADDR'):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # try to bind the socket, retry if necessary
        while not self.haveSocket and self.isRunning:
            try:
                self.socket.bind((self.ipAddr, self.port))
                self.socket.settimeout(0.5)
                self.haveSocket = True

            except socket.error, e:
                error, message = e.args

                # special handle for EADDRINUSE
                if error == errno.EADDRINUSE:
                    pymt_logger.error(
                        'OSC: Address %s:%i already in use, retry in 2 second'
                        % (self.ipAddr, self.port))
                else:
                    pymt_logger.exception(e)
                self.haveSocket = False

                # sleep 2 second before retry
                time.sleep(2)
Ejemplo n.º 8
0
    def createNode(self, node):
        from xml.dom import Node
        factory = MTWidgetFactory.get
        if node.nodeType == Node.ELEMENT_NODE:
            class_name = node.nodeName

            # parameters
            k = {}
            widget_id = None
            for name, value in node.attributes.items():
                name = str(name)
                if name == 'id':
                    widget_id = eval(value)
                else:
                    if name == 'xid':
                        name = 'id'
                    k[name] = eval(value)

            # create widget
            try:
                nodeWidget = factory(class_name)(**k)
                if widget_id is not None:
                    self.registerdb[widget_id] = nodeWidget
            except:
                pymt_logger.exception('XMLWidget: unable to create widget %s' \
                                      % class_name)
                raise

            # add child widgets
            for c in node.childNodes:
                w = self.createNode(c)
                if w:
                    nodeWidget.add_widget(w)

            return nodeWidget
Ejemplo n.º 9
0
    def run(self):
        self.haveSocket = False
        # create socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # fix trouble if python leave without cleaning well the socket
        # not needed under windows, he can reuse addr even if the socket
        # are in fin2 or wait state.
        if os.name in ['posix', 'mac'] and hasattr(socket, 'SO_REUSEADDR'):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # try to bind the socket, retry if necessary
        while not self.haveSocket and self.isRunning:
            try :
                self.socket.bind((self.ipAddr, self.port))
                self.socket.settimeout(0.5)
                self.haveSocket = True

            except socket.error, e:
                error, message = e.args

                # special handle for EADDRINUSE
                if error == errno.EADDRINUSE:
                    pymt_logger.error('OSC: Address %s:%i already in use, retry in 2 second' % (self.ipAddr, self.port))
                else:
                    pymt_logger.exception(e)
                self.haveSocket = False

                # sleep 2 second before retry
                time.sleep(2)
Ejemplo n.º 10
0
Archivo: svg.py Proyecto: Markitox/pymt
    def _set_filename(self, filename):
        global squirtle
        if squirtle is None:
            import squirtle
		# TODO remove this ugly code, improve loader for this
        try:
            pymt_logger.debug('SVGButton: loading %s' % filename)
            self.svg = squirtle.SVG(filename)
        except Exception, e:
            try:
                svgpath = os.path.join(pymt_data_dir, 'icons/svg')
                pymt_logger.exception('SVGButton: unable to load %s' % filename)
                pymt_logger.warning('SVGButton: trying %s' % (
                    svgpath + filename))
                self.svg = squirtle.SVG(os.path.join(svgpath, filename))
            except Exception, e:
                pymt_logger.exception('SVGButton: unable to load file %s' % filename)
Ejemplo n.º 11
0
 def parse_doc(self):
     self.paths = []
     self.width = self.parse_float(self.tree._root.get("width", '0'))
     self.height = self.parse_float(self.tree._root.get("height", '0'))
     if self.height:
         self.transform = Matrix([1, 0, 0, -1, 0, self.height])
     else:
         x, y, w, h = (self.parse_float(x) for x in parse_list(self.tree._root.get("viewBox")))
         self.transform = Matrix([1, 0, 0, -1, -x, h + y])
         self.height = h
         self.width = w
     self.opacity = 1.0
     for e in self.tree._root.getchildren():
         try:
             self.parse_element(e)
         except Exception, ex:
             pymt_logger.exception('Squirtle: exception while parsing element %s' % e)
             raise
Ejemplo n.º 12
0
    def _set_filename(self, filename):
        global squirtle
        if squirtle is None:
            import squirtle
# TODO remove this ugly code, improve loader for this
        try:
            pymt_logger.debug('SVGButton: loading %s' % filename)
            self.svg = squirtle.SVG(filename)
        except Exception, e:
            try:
                svgpath = os.path.join(pymt_data_dir, 'icons/svg')
                pymt_logger.exception('SVGButton: unable to load %s' %
                                      filename)
                pymt_logger.warning('SVGButton: trying %s' %
                                    (svgpath + filename))
                self.svg = squirtle.SVG(os.path.join(svgpath, filename))
            except Exception, e:
                pymt_logger.exception('SVGButton: unable to load file %s' %
                                      filename)
Ejemplo n.º 13
0
class OSCServer(_OSCServer):
    def __init__(self, **kwargs):
        kwargs.setdefault('ipAddr', '127.0.0.1')
        kwargs.setdefault('port', 9001)
        super(OSCServer, self).__init__()
        self.ipAddr = kwargs.get('ipAddr')
        self.port = kwargs.get('port')

    def run(self):
        self.haveSocket = False
        # create socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # fix trouble if python leave without cleaning well the socket
        # not needed under windows, he can reuse addr even if the socket
        # are in fin2 or wait state.
        if os.name in ['posix', 'mac'] and hasattr(socket, 'SO_REUSEADDR'):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # try to bind the socket, retry if necessary
        while not self.haveSocket and self.isRunning:
            try:
                self.socket.bind((self.ipAddr, self.port))
                self.socket.settimeout(0.5)
                self.haveSocket = True

            except socket.error, e:
                error, message = e.args

                # special handle for EADDRINUSE
                if error == errno.EADDRINUSE:
                    pymt_logger.error(
                        'OSC: Address %s:%i already in use, retry in 2 second'
                        % (self.ipAddr, self.port))
                else:
                    pymt_logger.exception(e)
                self.haveSocket = False

                # sleep 2 second before retry
                time.sleep(2)

        pymt_logger.info('OSC: listening for Tuio on %s:%i' %
                         (self.ipAddr, self.port))

        while self.isRunning:
            try:
                message = self.socket.recv(65535)
                self._queue_message(message)
            except Exception, e:
                if type(e) == socket.timeout:
                    continue
                pymt_logger.error('OSC: Error in Tuio recv()')
                pymt_logger.exception(e)
                return 'no data arrived'
Ejemplo n.º 14
0
 def parse_doc(self):
     self.paths = []
     self.width = self.parse_float(self.tree._root.get("width", '0'))
     self.height = self.parse_float(self.tree._root.get("height", '0'))
     if self.height:
         self.transform = Matrix([1, 0, 0, -1, 0, self.height])
     else:
         x, y, w, h = (self.parse_float(x)
                       for x in parse_list(self.tree._root.get("viewBox")))
         self.transform = Matrix([1, 0, 0, -1, -x, h + y])
         self.height = h
         self.width = w
     self.opacity = 1.0
     for e in self.tree._root.getchildren():
         try:
             self.parse_element(e)
         except Exception, ex:
             pymt_logger.exception(
                 'Squirtle: exception while parsing element %s' % e)
             raise
Ejemplo n.º 15
0
    def __init__(self, **kwargs):
        super(MTScatter, self).__init__(**kwargs)

        self.register_event_type('on_transform')

        # private properties
        self._touches = []
        self._last_touch_pos = {}
        self._do_rotation = True
        self._do_scale = True
        self._do_translation = True
        self._do_translation_x = True
        self._do_translation_y = True

        self._transform        = identity_matrix()
        self._transform_inv    = identity_matrix()
        self._transform_gl     = ascontiguousarray(identity_matrix().T,
                                                   dtype='float32')
        self._transform_inv_gl = ascontiguousarray(identity_matrix().T,
                                                   dtype='float32')
        self.update_matrices()

        #enable/dissable features
        self.auto_bring_to_front = kwargs.get('auto_bring_to_front', True)
        self.do_translation = kwargs.get('do_translation', True)
        self.do_rotation    = kwargs.get('do_rotation', True)
        self.scale_min      = kwargs.get('scale_min', 0.01)
        self.scale_max      = kwargs.get('scale_max', 1e20)
        self.do_scale       = kwargs.get('do_scale', True)

        #inital transformation
        self.scale = kwargs.get('scale', 1)
        self.rotation = kwargs.get('rotation', 0)
        if kwargs.get('pos') and kwargs.get('center'):
            pymt_logger.exception('both "pos" and "center" set in MTScatter'
                                  'constructor, only use one of the two!')
        if kwargs.get('pos'):
            self.pos = kwargs.get('pos')
        if kwargs.get('center'):
            self.pos = kwargs.get('center')
Ejemplo n.º 16
0
    def __init__(self, **kwargs):
        super(MTScatter, self).__init__(**kwargs)

        self.register_event_type('on_transform')

        # private properties
        self._touches = []
        self._last_touch_pos = {}
        self._do_rotation = True
        self._do_scale = True
        self._do_translation = True
        self._do_translation_x = True
        self._do_translation_y = True

        self._transform = identity_matrix()
        self._transform_inv = identity_matrix()
        self._transform_gl = ascontiguousarray(identity_matrix().T,
                                               dtype='float32')
        self._transform_inv_gl = ascontiguousarray(identity_matrix().T,
                                                   dtype='float32')
        self.update_matrices()

        #enable/dissable features
        self.auto_bring_to_front = kwargs.get('auto_bring_to_front', True)
        self.do_translation = kwargs.get('do_translation', True)
        self.do_rotation = kwargs.get('do_rotation', True)
        self.scale_min = kwargs.get('scale_min', 0.01)
        self.scale_max = kwargs.get('scale_max', 1e20)
        self.do_scale = kwargs.get('do_scale', True)

        #inital transformation
        self.scale = kwargs.get('scale', 1)
        self.rotation = kwargs.get('rotation', 0)
        if kwargs.get('pos') and kwargs.get('center'):
            pymt_logger.exception('both "pos" and "center" set in MTScatter'
                                  'constructor, only use one of the two!')
        if kwargs.get('pos'):
            self.pos = kwargs.get('pos')
        if kwargs.get('center'):
            self.pos = kwargs.get('center')
Ejemplo n.º 17
0
 def extract(v):
     sname, svalue = v.split(':')
     name = sname.strip()
     value = svalue.strip()
     if name not in css_keyword_convert:
         # searching for a state
         for state in pymt_css_states:
             if name.endswith(state):
                 name = name[:-len(state)]
                 break
         # searching for a prefix
         for prefix in pymt_css_prefix:
             if name.startswith(prefix):
                 name = name[len(prefix):]
                 break
     if name in css_keyword_convert:
         try:
             value = css_keyword_convert[name](value)
         except Exception:
             pymt_logger.exception(
                 'Error while convert %s: %s' % (name, value))
     return sname.strip(), value
Ejemplo n.º 18
0
def _screenshot():
    import os
    import pygame
    from OpenGL.GL import glReadBuffer, glReadPixels, GL_RGB, GL_UNSIGNED_BYTE, GL_FRONT
    win = getWindow()
    glReadBuffer(GL_FRONT)
    data = glReadPixels(0, 0, win.width, win.height, GL_RGB, GL_UNSIGNED_BYTE)
    surface = pygame.image.fromstring(str(buffer(data)), win.size, 'RGB', True)
    filename = None
    for i in xrange(9999):
        path = os.path.join(os.getcwd(), 'screenshot%04d.jpg' % i)
        if not os.path.exists(path):
            filename = path
            break
    if filename:
        try:
            pygame.image.save(surface, filename)
            pymt_logger.info('KeyBinding: Screenshot saved at %s' % filename)
        except:
            pymt_logger.exception('KeyBinding: Unable to take a screenshot')
    else:
        pymt_logger.warning('KeyBinding: Unable to take screenshot, no more slot available')
Ejemplo n.º 19
0
Archivo: svg.py Proyecto: Markitox/pymt
 def _set_filename(self, filename):
     global squirtle
     if squirtle is None:
         import squirtle
     # TODO remove this ugly code, improve loader for this
     try:
         if self.rawdata is None:
             pymt_logger.debug('SVG: loading %s' % filename)
             self.svg = squirtle.SVG(filename)
         else:
             pymt_logger.debug('SVG: loading %s from rawdata' % filename)
             self.svg = squirtle.SVG(filename=filename, rawdata=self.rawdata)
     except Exception:
         try:
             svgpath = os.path.join(pymt_data_dir, 'icons/svg')
             pymt_logger.exception('SVG: unable to load %s' % filename)
             pymt_logger.warning('SVG: trying %s' % (svgpath + filename))
             self.svg = squirtle.SVG(os.path.join(svgpath, filename))
         except Exception:
             pymt_logger.exception('SVG: unable to load file %s' % filename)
             self._filename = filename
             self.size = (self.svg.width, self.svg.height)
Ejemplo n.º 20
0
 def lambda_connect(*largs):
     if type(p2) in (tuple, list):
         if len(largs) != len(p2):
             pymt_logger.exception('Widget: cannot connect with'
                                   'different size')
             raise
         for p in p2:
             if p is None:
                 continue
             w2.__setattr__(p, type(w2.__getattribute__(p))(
                 func(largs[p2.index(p)])))
     else:
         dtype = type(w2.__getattribute__(p2))
         try:
             if len(largs) == 1:
                 w2.__setattr__(p2, dtype(func(*largs)))
             else:
                 w2.__setattr__(p2, dtype(func(largs)))
         except Exception:
             pymt_logger.exception('Widget: cannot connect with'
                                   'different size')
             raise
Ejemplo n.º 21
0
 def _set_filename(self, filename):
     global squirtle
     if squirtle is None:
         import squirtle
     # TODO remove this ugly code, improve loader for this
     try:
         if self.rawdata is None:
             pymt_logger.debug('SVG: loading %s' % filename)
             self.svg = squirtle.SVG(filename)
         else:
             pymt_logger.debug('SVG: loading %s from rawdata' % filename)
             self.svg = squirtle.SVG(filename=filename,
                                     rawdata=self.rawdata)
     except Exception:
         try:
             svgpath = os.path.join(pymt_data_dir, 'icons/svg')
             pymt_logger.exception('SVG: unable to load %s' % filename)
             pymt_logger.warning('SVG: trying %s' % (svgpath + filename))
             self.svg = squirtle.SVG(os.path.join(svgpath, filename))
         except Exception:
             pymt_logger.exception('SVG: unable to load file %s' % filename)
             self._filename = filename
             self.size = (self.svg.width, self.svg.height)
Ejemplo n.º 22
0
def _screenshot():
    import os
    import pygame
    from OpenGL.GL import glReadBuffer, glReadPixels, GL_RGB, GL_UNSIGNED_BYTE, GL_FRONT
    win = getWindow()
    glReadBuffer(GL_FRONT)
    data = glReadPixels(0, 0, win.width, win.height, GL_RGB, GL_UNSIGNED_BYTE)
    surface = pygame.image.fromstring(str(buffer(data)), win.size, 'RGB', True)
    filename = None
    for i in xrange(9999):
        path = os.path.join(os.getcwd(), 'screenshot%04d.jpg' % i)
        if not os.path.exists(path):
            filename = path
            break
    if filename:
        try:
            pygame.image.save(surface, filename)
            pymt_logger.info('KeyBinding: Screenshot saved at %s' % filename)
        except:
            pymt_logger.exception('KeyBinding: Unable to take a screenshot')
    else:
        pymt_logger.warning(
            'KeyBinding: Unable to take screenshot, no more slot available')
Ejemplo n.º 23
0
 def lambda_connect(*largs):
     if type(p2) in (tuple, list):
         if len(largs) != len(p2):
             pymt_logger.exception('Widget: cannot connect with'
                                   'different size')
             raise
         for p in p2:
             if p is None:
                 continue
             w2.__setattr__(
                 p,
                 type(w2.__getattribute__(p))(func(largs[p2.index(p)])))
     else:
         dtype = type(w2.__getattribute__(p2))
         try:
             if len(largs) == 1:
                 w2.__setattr__(p2, dtype(func(*largs)))
             else:
                 w2.__setattr__(p2, dtype(func(largs)))
         except Exception:
             pymt_logger.exception('Widget: cannot connect with'
                                   'different size')
             raise
Ejemplo n.º 24
0
    def parse_element(self, e):
        default = object()
        self.fill = parse_color(e.get('fill'), default)
        self.stroke = parse_color(e.get('stroke'), default)
        oldopacity = self.opacity
        self.opacity *= float(e.get('opacity', 1))
        fill_opacity = float(e.get('fill-opacity', 1))
        stroke_opacity = float(e.get('stroke-opacity', 1))

        oldtransform = self.transform
        self.transform = self.transform * Matrix(e.get('transform'))

        style = e.get('style')
        if style:
            sdict = parse_style(style)
            if 'fill' in sdict:
                self.fill = parse_color(sdict['fill'])
            if 'fill-opacity' in sdict:
                fill_opacity *= float(sdict['fill-opacity'])
            if 'stroke' in sdict:
                self.stroke = parse_color(sdict['stroke'])
            if 'stroke-opacity' in sdict:
                stroke_opacity *= float(sdict['stroke-opacity'])
        if self.fill == default:
            self.fill = [0, 0, 0, 255]
        if self.stroke == default:
            self.stroke = [0, 0, 0, 0]
        if isinstance(self.stroke, list):
            self.stroke[3] = int(self.opacity * stroke_opacity * self.stroke[3])
        if isinstance(self.fill, list):
            self.fill[3] = int(self.opacity * fill_opacity * self.fill[3])
        if isinstance(self.stroke, list) and self.stroke[3] == 0: self.stroke = self.fill #Stroked edges antialias better

        if e.tag.endswith('path'):
            pathdata = e.get('d', '')
            pathdata = re.findall("([A-Za-z]|-?[0-9]+\.?[0-9]*(?:e-?[0-9]*)?)", pathdata)

            def pnext():
                return (float(pathdata.pop(0)), float(pathdata.pop(0)))

            self.new_path()
            while pathdata:
                opcode = pathdata.pop(0)
                if opcode == 'M':
                    self.set_position(*pnext())
                elif opcode == 'C':
                    self.curve_to(*(pnext() + pnext() + pnext()))
                elif opcode == 'c':
                    mx = self.x
                    my = self.y
                    x1, y1 = pnext()
                    x2, y2 = pnext()
                    x, y = pnext()

                    self.curve_to(mx + x1, my + y1, mx + x2, my + y2, mx + x, my + y)
                elif opcode == 'S':
                    self.curve_to(2 * self.x - self.last_cx, 2 * self.y - self.last_cy, *(pnext() + pnext()))
                elif opcode == 's':
                    mx = self.x
                    my = self.y
                    x1, y1 = 2 * self.x - self.last_cx, 2 * self.y - self.last_cy
                    x2, y2 = pnext()
                    x, y = pnext()

                    self.curve_to(x1, y1, mx + x2, my + y2, mx + x, my + y)
                elif opcode == 'A':
                    rx, ry = pnext()
                    phi = float(pathdata.pop(0))
                    large_arc = int(pathdata.pop(0))
                    sweep = int(pathdata.pop(0))
                    x, y = pnext()
                    self.arc_to(rx, ry, phi, large_arc, sweep, x, y)
                elif opcode in 'zZ':
                    self.close_path()
                elif opcode == 'L':
                    self.line_to(*pnext())
                elif opcode == 'l':
                    x, y = pnext()
                    self.line_to(self.x + x, self.y + y)
                elif opcode == 'H':
                    x = float(pathdata.pop(0))
                    self.line_to(x, self.y)
                elif opcode == 'h':
                    x = float(pathdata.pop(0))
                    self.line_to(self.x + x, self.y)
                elif opcode == 'V':
                    y = float(pathdata.pop(0))
                    self.line_to(self.x, y)
                elif opcode == 'v':
                    y = float(pathdata.pop(0))
                    self.line_to(self.x, self.y + y)
                else:
                    self.warn("Unrecognised opcode: " + opcode)
            self.end_path()
        elif e.tag.endswith('rect'):
            x = 0
            y = 0
            if 'x' in e.keys():
                x = float(e.get('x'))
            if 'y' in e.keys():
                y = float(e.get('y'))
            h = float(e.get('height'))
            w = float(e.get('width'))
            self.new_path()
            self.set_position(x, y)
            self.line_to(x+w,y)
            self.line_to(x+w,y+h)
            self.line_to(x,y+h)
            self.line_to(x,y)
            self.end_path()
        elif e.tag.endswith('polyline') or e.tag.endswith('polygon'):
            pathdata = e.get('points')
            pathdata = re.findall("(-?[0-9]+\.?[0-9]*(?:e-?[0-9]*)?)", pathdata)
            def pnext():
                return (float(pathdata.pop(0)), float(pathdata.pop(0)))
            self.new_path()
            while pathdata:
                self.line_to(*pnext())
            if e.tag.endswith('polygon'):
                self.close_path()
            self.end_path()
        elif e.tag.endswith('line'):
            x1 = float(e.get('x1'))
            y1 = float(e.get('y1'))
            x2 = float(e.get('x2'))
            y2 = float(e.get('y2'))
            self.new_path()
            self.set_position(x1, y1)
            self.line_to(x2, y2)
            self.end_path()
        elif e.tag.endswith('circle'):
            cx = float(e.get('cx'))
            cy = float(e.get('cy'))
            r = float(e.get('r'))
            self.new_path()
            for i in xrange(self.circle_points):
                theta = 2 * i * math.pi / self.circle_points
                self.line_to(cx + r * math.cos(theta), cy + r * math.sin(theta))
            self.close_path()
            self.end_path()
        elif e.tag.endswith('ellipse'):
            cx = float(e.get('cx'))
            cy = float(e.get('cy'))
            rx = float(e.get('rx'))
            ry = float(e.get('ry'))
            self.new_path()
            for i in xrange(self.circle_points):
                theta = 2 * i * math.pi / self.circle_points
                self.line_to(cx + rx * math.cos(theta), cy + ry * math.sin(theta))
            self.close_path()
            self.end_path()
        elif e.tag.endswith('linearGradient'):
            self.gradients[e.get('id')] = LinearGradient(e, self)
        elif e.tag.endswith('radialGradient'):
            self.gradients[e.get('id')] = RadialGradient(e, self)
        for c in e.getchildren():
            try:
                self.parse_element(c)
            except Exception, ex:
                pymt_logger.exception('Squirtle: exception while parsing element %s' % c)
                raise
Ejemplo n.º 25
0
    def parse_element(self, e):
        default = object()
        self.fill = parse_color(e.get('fill'), default)
        self.stroke = parse_color(e.get('stroke'), default)
        oldopacity = self.opacity
        self.opacity *= float(e.get('opacity', 1))
        fill_opacity = float(e.get('fill-opacity', 1))
        stroke_opacity = float(e.get('stroke-opacity', 1))

        oldtransform = self.transform
        self.transform = self.transform * Matrix(e.get('transform'))

        style = e.get('style')
        if style:
            sdict = parse_style(style)
            if 'fill' in sdict:
                self.fill = parse_color(sdict['fill'])
            if 'fill-opacity' in sdict:
                fill_opacity *= float(sdict['fill-opacity'])
            if 'stroke' in sdict:
                self.stroke = parse_color(sdict['stroke'])
            if 'stroke-opacity' in sdict:
                stroke_opacity *= float(sdict['stroke-opacity'])
        if self.fill == default:
            self.fill = [0, 0, 0, 255]
        if self.stroke == default:
            self.stroke = [0, 0, 0, 0]
        if isinstance(self.stroke, list):
            self.stroke[3] = int(self.opacity * stroke_opacity *
                                 self.stroke[3])
        if isinstance(self.fill, list):
            self.fill[3] = int(self.opacity * fill_opacity * self.fill[3])
        if isinstance(self.stroke, list) and self.stroke[3] == 0:
            self.stroke = self.fill  #Stroked edges antialias better

        if e.tag.endswith('path'):
            pathdata = e.get('d', '')
            pathdata = re.findall("([A-Za-z]|-?[0-9]+\.?[0-9]*(?:e-?[0-9]*)?)",
                                  pathdata)

            def pnext():
                return (float(pathdata.pop(0)), float(pathdata.pop(0)))

            self.new_path()
            while pathdata:
                opcode = pathdata.pop(0)
                if opcode == 'M':
                    self.set_position(*pnext())
                elif opcode == 'C':
                    self.curve_to(*(pnext() + pnext() + pnext()))
                elif opcode == 'c':
                    mx = self.x
                    my = self.y
                    x1, y1 = pnext()
                    x2, y2 = pnext()
                    x, y = pnext()

                    self.curve_to(mx + x1, my + y1, mx + x2, my + y2, mx + x,
                                  my + y)
                elif opcode == 'S':
                    self.curve_to(2 * self.x - self.last_cx,
                                  2 * self.y - self.last_cy,
                                  *(pnext() + pnext()))
                elif opcode == 's':
                    mx = self.x
                    my = self.y
                    x1, y1 = 2 * self.x - self.last_cx, 2 * self.y - self.last_cy
                    x2, y2 = pnext()
                    x, y = pnext()

                    self.curve_to(x1, y1, mx + x2, my + y2, mx + x, my + y)
                elif opcode == 'A':
                    rx, ry = pnext()
                    phi = float(pathdata.pop(0))
                    large_arc = int(pathdata.pop(0))
                    sweep = int(pathdata.pop(0))
                    x, y = pnext()
                    self.arc_to(rx, ry, phi, large_arc, sweep, x, y)
                elif opcode in 'zZ':
                    self.close_path()
                elif opcode == 'L':
                    self.line_to(*pnext())
                elif opcode == 'l':
                    x, y = pnext()
                    self.line_to(self.x + x, self.y + y)
                elif opcode == 'H':
                    x = float(pathdata.pop(0))
                    self.line_to(x, self.y)
                elif opcode == 'h':
                    x = float(pathdata.pop(0))
                    self.line_to(self.x + x, self.y)
                elif opcode == 'V':
                    y = float(pathdata.pop(0))
                    self.line_to(self.x, y)
                elif opcode == 'v':
                    y = float(pathdata.pop(0))
                    self.line_to(self.x, self.y + y)
                else:
                    self.warn("Unrecognised opcode: " + opcode)
            self.end_path()
        elif e.tag.endswith('rect'):
            x = 0
            y = 0
            if 'x' in e.keys():
                x = float(e.get('x'))
            if 'y' in e.keys():
                y = float(e.get('y'))
            h = float(e.get('height'))
            w = float(e.get('width'))
            self.new_path()
            self.set_position(x, y)
            self.line_to(x + w, y)
            self.line_to(x + w, y + h)
            self.line_to(x, y + h)
            self.line_to(x, y)
            self.end_path()
        elif e.tag.endswith('polyline') or e.tag.endswith('polygon'):
            pathdata = e.get('points')
            pathdata = re.findall("(-?[0-9]+\.?[0-9]*(?:e-?[0-9]*)?)",
                                  pathdata)

            def pnext():
                return (float(pathdata.pop(0)), float(pathdata.pop(0)))

            self.new_path()
            while pathdata:
                self.line_to(*pnext())
            if e.tag.endswith('polygon'):
                self.close_path()
            self.end_path()
        elif e.tag.endswith('line'):
            x1 = float(e.get('x1'))
            y1 = float(e.get('y1'))
            x2 = float(e.get('x2'))
            y2 = float(e.get('y2'))
            self.new_path()
            self.set_position(x1, y1)
            self.line_to(x2, y2)
            self.end_path()
        elif e.tag.endswith('circle'):
            cx = float(e.get('cx'))
            cy = float(e.get('cy'))
            r = float(e.get('r'))
            self.new_path()
            for i in xrange(self.circle_points):
                theta = 2 * i * math.pi / self.circle_points
                self.line_to(cx + r * math.cos(theta),
                             cy + r * math.sin(theta))
            self.close_path()
            self.end_path()
        elif e.tag.endswith('ellipse'):
            cx = float(e.get('cx'))
            cy = float(e.get('cy'))
            rx = float(e.get('rx'))
            ry = float(e.get('ry'))
            self.new_path()
            for i in xrange(self.circle_points):
                theta = 2 * i * math.pi / self.circle_points
                self.line_to(cx + rx * math.cos(theta),
                             cy + ry * math.sin(theta))
            self.close_path()
            self.end_path()
        elif e.tag.endswith('linearGradient'):
            self.gradients[e.get('id')] = LinearGradient(e, self)
        elif e.tag.endswith('radialGradient'):
            self.gradients[e.get('id')] = RadialGradient(e, self)
        for c in e.getchildren():
            try:
                self.parse_element(c)
            except Exception, ex:
                pymt_logger.exception(
                    'Squirtle: exception while parsing element %s' % c)
                raise
Ejemplo n.º 26
0
                return
            self.add_section(section)

        def write(self):
            with open(pymt_config_fn, 'w') as fd:
                ConfigParser.write(self, fd)

    # Create default configuration
    pymt_config = PyMTConfigParser()

    # Read config file if exist
    if os.path.exists(pymt_config_fn):
        try:
            pymt_config.read(pymt_config_fn)
        except Exception, e:
            pymt_logger.exception('Core: error while reading local'
                                  'configuration')

    pymt_config_version = pymt_config.getdefault('pymt', 'config_version', 0)

    # Add defaults section
    pymt_config.adddefaultsection('pymt')
    pymt_config.adddefaultsection('keyboard')
    pymt_config.adddefaultsection('graphics')
    pymt_config.adddefaultsection('input')
    pymt_config.adddefaultsection('dump')
    pymt_config.adddefaultsection('modules')
    pymt_config.adddefaultsection('widgets')

    # Upgrade default configuration until having the current version
    need_save = False
    if pymt_config_version != PYMT_CONFIG_VERSION:
Ejemplo n.º 27
0
}

# Read environment
for option in pymt_options:
    key = 'PYMT_%s' % option.upper()
    if key in os.environ:
        try:
            if type(pymt_options[option]) in (list, tuple):
                pymt_options[option] = (str(os.environ[key]), )
            else:
                pymt_options[option] = os.environ[key].lower() in \
                    ('true', '1', 'yes', 'yup')
        except Exception:
            pymt_logger.warning('Core: Wrong value for %s'
                                'environment key' % key)
            pymt_logger.exception('')

# Extract all needed path in pymt
#: PyMT directory
pymt_base_dir = os.path.dirname(sys.modules[__name__].__file__)
#: PyMT external libraries directory
pymt_libs_dir = os.path.join(pymt_base_dir, 'lib')
#: PyMT modules directory
pymt_modules_dir = os.path.join(pymt_base_dir, 'modules')
#: PyMT data directory
pymt_data_dir = os.path.join(pymt_base_dir, 'data')
#: PyMT input provider directory
pymt_providers_dir = os.path.join(pymt_base_dir, 'input', 'providers')
#: PyMT icons config path (don't remove last '')
pymt_icons_dir = os.path.join(pymt_data_dir, 'icons', '')
#: PyMT user-home storage directory
Ejemplo n.º 28
0
}

# Read environment
for option in pymt_options:
    key = 'PYMT_%s' % option.upper()
    if key in os.environ:
        try:
            if type(pymt_options[option]) in (list, tuple):
                pymt_options[option] = (str(os.environ[key]),)
            else:
                pymt_options[option] = os.environ[key].lower() in \
                    ('true', '1', 'yes', 'yup')
        except Exception:
            pymt_logger.warning('Core: Wrong value for %s'
                                'environment key' % key)
            pymt_logger.exception('')

# Extract all needed path in pymt
#: PyMT directory
pymt_base_dir        = os.path.dirname(sys.modules[__name__].__file__)
#: PyMT external libraries directory
pymt_libs_dir        = os.path.join(pymt_base_dir, 'lib')
#: PyMT modules directory
pymt_modules_dir     = os.path.join(pymt_base_dir, 'modules')
#: PyMT data directory
pymt_data_dir        = os.path.join(pymt_base_dir, 'data')
#: PyMT input provider directory
pymt_providers_dir   = os.path.join(pymt_base_dir, 'input', 'providers')
#: PyMT icons config path (don't remove last '')
pymt_icons_dir        = os.path.join(pymt_data_dir, 'icons', '')
#: PyMT user-home storage directory
Ejemplo n.º 29
0
                return
            self.add_section(section)

        def write(self):
            with open(pymt_config_fn, 'w') as fd:
                ConfigParser.write(self, fd)

    # Create default configuration
    pymt_config = PyMTConfigParser()

    # Read config file if exist
    if os.path.exists(pymt_config_fn):
        try:
            pymt_config.read(pymt_config_fn)
        except Exception, e:
            pymt_logger.exception('Core: error while reading local'
                                  'configuration')

    pymt_config_version = pymt_config.getdefault('pymt', 'config_version', 0)

    # Add defaults section
    pymt_config.adddefaultsection('pymt')
    pymt_config.adddefaultsection('keyboard')
    pymt_config.adddefaultsection('graphics')
    pymt_config.adddefaultsection('input')
    pymt_config.adddefaultsection('dump')
    pymt_config.adddefaultsection('modules')
    pymt_config.adddefaultsection('widgets')

    # Upgrade default configuration until having the current version
    need_save = False
    if pymt_config_version != PYMT_CONFIG_VERSION: