def decode_vector(self, img):
		self.data = [None] * (self.size ** 2)
		self.transform = img.attrib['transform']
		self.pos = (float('inf'), float('inf'))

		pixels = img.xpath('//svg:rect', namespaces=inkex.NSS)
		paths = img.xpath('//svg:path', namespaces=inkex.NSS)

		# Because svg groups have no set x,y coords we have to decern the
		# position from the contents which we can then use as an offset when
		# reconstructing the image.
		for pixel in pixels + paths:
			pos = (inkex.unittouu(pixel.attrib['x']),
				   inkex.unittouu(pixel.attrib['y']))
			self.pos[0] = self.pos[0] if self.pos[0] < pos[0] else pos[0]
			self.pos[1] = self.pos[1] if self.pos[1] < pos[1] else pos[1]

		for pixel in pixels:
			style = simplestyle.parseStyle(pixel.attrib['style'])
			pos = (inkex.unittouu(pixel.attrib['x']) - self.pos[0],
				   inkex.unittouu(pixel.attrib['y']) - self.pos[1])
			index = pos2index(self.size, *pos)
			self.data[index] = simplestyle.parseColor(style['fill'])

		last_point = (0, 0)
		for path in paths:
			for offset in re.findall('m\s(?P<x>-?\d+),(?P<y>-?\d+).*?z'):
				style = simplestyle.parseStyle(pixel.attrib['style'])
				pos = (inkex.unittouu(path.attrib['x']) - self.pos[0] + last_point[0],
					   inkex.unittouu(path.attrib['y']) - self.pos[1] + last_point[1])
				index = pos2index(self.size, *pos)
				self.data[index] = simplestyle.parseColor(style['fill'])

				last_point[0] += offset[0]
				last_point[1] += offset[1]
Example #2
0
    def groupToPath(self, node, doReplace=True):
        if node.tag == inkex.addNS('g', 'svg'):
            newNode = inkex.etree.SubElement(self.current_layer,
                                             inkex.addNS('path', 'svg'))

            newstyle = simplestyle.parseStyle(node.get('style') or "")
            newp = []
            for child in node:
                childstyle = simplestyle.parseStyle(child.get('style') or "")
                childstyle.update(newstyle)
                newstyle.update(childstyle)
                childAsPath = self.objectToPath(child, False)
                newp += cubicsuperpath.parsePath(childAsPath.get('d'))
            newNode.set('d', cubicsuperpath.formatPath(newp))
            newNode.set('style', simplestyle.formatStyle(newstyle))

            self.current_layer.remove(newNode)
            if doReplace:
                parent = node.getparent()
                parent.insert(parent.index(node), newNode)
                parent.remove(node)

            return newNode
        else:
            raise AssertionError
Example #3
0
def check_text_on_path(svg, element, scale_x, scale_y):
    """Check whether to skip scaling a text put on a path."""
    skip = False
    path = get_linked(svg, element.find(inkex.addNS('textPath', 'svg')))
    if not is_in_defs(svg, path):
        if is_sibling(element, path):
            # skip common element scaling if both text and path are siblings
            skip = True
            # scale offset
            if 'transform' in element.attrib:
                mat = simpletransform.parseTransform(element.get('transform'))
                mat[0][2] *= scale_x
                mat[1][2] *= scale_y
                element.set('transform', simpletransform.formatTransform(mat))
            # scale font size
            mat = simpletransform.parseTransform(
                'scale({},{})'.format(scale_x, scale_y))
            det = abs(mat[0][0]*mat[1][1] - mat[0][1]*mat[1][0])
            descrim = math.sqrt(abs(det))
            prop = 'font-size'
            # outer text
            sdict = simplestyle.parseStyle(element.get('style'))
            if prop in sdict:
                sdict[prop] = float(sdict[prop]) * descrim
                element.set('style', simplestyle.formatStyle(sdict))
            # inner tspans
            for child in element.iterdescendants():
                if child.tag == inkex.addNS('tspan', 'svg'): 
                    sdict = simplestyle.parseStyle(child.get('style'))
                    if prop in sdict:
                        sdict[prop] = float(sdict[prop]) * descrim
                        child.set('style', simplestyle.formatStyle(sdict))
    return skip
Example #4
0
    def import_group_color_style(self, src_svg_ele):
        """
        Extracts the color relevant style attributes of src_svg_ele (of class SVGElement) and applies them to all items
        of self._node. Ensures that non color relevant style attributes are not overwritten.
        """

        # Take the top level style information which is set when coloring the group in Inkscape
        src_style_string = src_svg_ele._node.get("style")

        # If a style attribute exists we can copy the style, if not, there is nothing to do here
        if src_style_string:
            # Fetch the part of the source dict which is interesting for colorization
            src_style_dict = ss.parseStyle(src_style_string)
            color_style_dict = {key: value for key, value in src_style_dict.items() if
                                key.lower() in ["fill", "stroke", "opacity", "stroke-opacity",
                                                "fill-opacity"] and value.lower() != "none"}

            # Iterate over all nodes of self._node and apply the imported color style
            for dest_node in self._node.getiterator():
                dest_style_string = dest_node.attrib.get("style")
                if dest_style_string:
                    dest_style_dict = ss.parseStyle(dest_style_string)
                    for key, value in color_style_dict.items():
                        dest_style_dict[key] = value
                else:
                    dest_style_dict = color_style_dict
                dest_style_string = ss.formatStyle(dest_style_dict)
                dest_node.attrib["style"] = dest_style_string
Example #5
0
    def expandGroupsUnlinkClones(self,
                                 aList,
                                 transferTransform=True,
                                 doReplace=True):
        for id in aList.keys()[:]:
            node = aList[id]
            if node.tag == inkex.addNS('g', 'svg') or node.tag == 'g':
                self.expandGroups(aList, transferTransform)
                self.expandGroupsUnlinkClones(aList, transferTransform,
                                              doReplace)
                #Hum... not very efficient if there are many clones of groups...

            elif node.tag == inkex.addNS('use', 'svg') or node.tag == 'use':
                refnode = self.refNode(node)
                newnode = self.unlinkClone(node, doReplace)
                del aList[id]

                style = simplestyle.parseStyle(node.get('style') or "")
                refstyle = simplestyle.parseStyle(refnode.get('style') or "")
                style.update(refstyle)
                newnode.set('style', simplestyle.formatStyle(style))

                newid = newnode.get('id')
                aList.update(
                    self.expandGroupsUnlinkClones({newid: newnode},
                                                  transferTransform,
                                                  doReplace))
        return aList
Example #6
0
    def expandGroupsUnlinkClones(self,aList,transferTransform=True,doReplace=True):
        for id in aList.keys()[:]:     
            node=aList[id]
            if node.tagName == 'g':
                self.expandGroups(aList,transferTransform)
                self.expandGroupsUnlinkClones(aList,transferTransform,doReplace)
		#Hum... not very efficient if there are many clones of groups...
            elif node.tagName == 'use':
                refid=node.getAttributeNS(inkex.NSS[u'xlink'],'href')
                path = '//*[@id="%s"]' % refid[1:]
                refnode = xml.xpath.Evaluate(path,self.document)[0]
                newnode=refnode.cloneNode(True)
		self.recursNewIds(newnode)

		if node.hasAttributeNS(None,u'style'):
		    style=simplestyle.parseStyle(node.getAttributeNS(None,u'style'))
		    refstyle=simplestyle.parseStyle(refnode.getAttributeNS(None,u'style'))
		    style.update(refstyle)
		    newnode.setAttributeNS(None,'style',simplestyle.formatStyle(style))
                applyTransformToNode(parseTransform(node.getAttributeNS(None,'transform')),newnode)
                if doReplace:
                    parent=node.parentNode
                    parent.insertBefore(newnode,node)
                    parent.removeChild(node)
                del aList[id]
		newid=newnode.getAttributeNS(None,'id')
                aList.update(self.expandGroupsUnlinkClones({newid:newnode},transferTransform,doReplace))
        return aList
    def effect(self):
        defs = self.xpathSingle('/svg//defs')
        if not defs:
            defs = self.document.createElement('svg:defs')
            self.document.documentElement.appendChile(defs)

        for id, node in self.selected.iteritems():
            mprops = ['marker', 'marker-start', 'marker-mid', 'marker-end']
            try:
                style = simplestyle.parseStyle(
                    node.attributes.getNamedItem('style').value)
            except:
                inkex.debug("No style attribute found for id: %s" % id)
                continue

            stroke = style.get('stroke', '#000000')

            for mprop in mprops:
                if style.has_key(mprop) and style[mprop] != 'none' and style[
                        mprop][:5] == 'url(#':
                    marker_id = style[mprop][5:-1]
                    try:
                        old_mnode = self.xpathSingle(
                            '/svg//marker[@id="%s"]' % marker_id)
                        if not self.options.modify:
                            mnode = old_mnode.cloneNode(True)
                        else:
                            mnode = old_mnode
                    except:
                        inkex.debug("unable to locate marker: %s" % marker_id)
                        continue

                    new_id = self.uniqueId(marker_id, not self.options.modify)

                    style[mprop] = "url(#%s)" % new_id
                    mnode.attributes.getNamedItem('id').value = new_id
                    mnode.attributes.getNamedItemNS(inkex.NSS['inkscape'],
                                                    'stockid').value = new_id
                    defs.appendChild(mnode)

                    children = inkex.xml.xpath.Evaluate(
                        '/svg//marker[@id="%s"]//*[@style]' % new_id,
                        self.document,
                        context=self.ctx)
                    for child in children:
                        cstyle = simplestyle.parseStyle(
                            child.attributes.getNamedItem('style').value)
                        if ('stroke' in cstyle and cstyle['stroke'] != 'none'
                            ) or 'stroke' not in cstyle:
                            cstyle['stroke'] = stroke
                        if ('fill' in cstyle and cstyle['fill'] != 'none'
                            ) or 'fill' not in cstyle:
                            cstyle['fill'] = stroke
                        child.attributes.getNamedItem(
                            'style').value = simplestyle.formatStyle(cstyle)
            node.attributes.getNamedItem(
                'style').value = simplestyle.formatStyle(style)
    def effect(self):
        defs = self.xpathSingle('/svg//defs')
        if not defs:
            defs = self.document.createElement('svg:defs')
            self.document.documentElement.appendChile(defs)

        for id, node in self.selected.iteritems():
            mprops = ['marker', 'marker-start', 'marker-mid', 'marker-end']
            try:
                style = simplestyle.parseStyle(
                    node.attributes.getNamedItem('style').value)
            except:
                inkex.debug("No style attribute found for id: %s" % id)
                continue

            stroke = style.get('stroke', '#000000')

            for mprop in mprops:
                if style.has_key(mprop) and style[mprop] != 'none' and style[
                        mprop][:5] == 'url(#':
                    marker_id = style[mprop][5:-1]
                    try:
                        old_mnode = self.xpathSingle('/svg//marker[@id="%s"]' %
                                                     marker_id)
                        if not self.options.modify:
                            mnode = old_mnode.cloneNode(True)
                        else:
                            mnode = old_mnode
                    except:
                        inkex.debug("unable to locate marker: %s" % marker_id)
                        continue

                    new_id = self.uniqueId(marker_id, not self.options.modify)

                    style[mprop] = "url(#%s)" % new_id
                    mnode.attributes.getNamedItem('id').value = new_id
                    mnode.attributes.getNamedItemNS(inkex.NSS['inkscape'],
                                                    'stockid').value = new_id
                    defs.appendChild(mnode)

                    children = inkex.xml.xpath.Evaluate(
                        '/svg//marker[@id="%s"]//*[@style]' % new_id,
                        self.document,
                        context=self.ctx)
                    for child in children:
                        cstyle = simplestyle.parseStyle(
                            child.attributes.getNamedItem('style').value)
                        if ('stroke' in cstyle and cstyle['stroke'] != 'none'
                            ) or 'stroke' not in cstyle:
                            cstyle['stroke'] = stroke
                        if ('fill' in cstyle and cstyle['fill'] != 'none'
                            ) or 'fill' not in cstyle:
                            cstyle['fill'] = stroke
                        child.attributes.getNamedItem(
                            'style').value = simplestyle.formatStyle(cstyle)
            node.attributes.getNamedItem(
                'style').value = simplestyle.formatStyle(style)
Example #9
0
 def compareStyleWith(self, cmpNode):
     """
     Compares the styles of this nodes and another node.
     Returns True, if the 'style' attributes contain the same key/value pairs
     (regardless of their order, distinguishing upper/lower case).
     """
     cmpNode = Elem(cmpNode).getNode()
     assert self._node is not None
     assert cmpNode is not None
     key = 'style'
     style = simplestyle.parseStyle(self._node.attrib.get(key, None))
     cmpStyle = simplestyle.parseStyle(cmpNode.attrib.get(key, None))
     return style == cmpStyle
    def effect(self):
        defs = self.xpathSingle('/svg:svg//svg:defs')
        if defs == None:
            defs = inkex.etree.SubElement(self.document.getroot(),
                                          inkex.addNS('defs', 'svg'))

        for id, node in self.selected.iteritems():
            mprops = ['marker', 'marker-start', 'marker-mid', 'marker-end']
            try:
                style = simplestyle.parseStyle(node.get('style'))
            except:
                inkex.errormsg(_("No style attribute found for id: %s") % id)
                continue

            stroke = style.get('stroke', '#000000')

            for mprop in mprops:
                if style.has_key(mprop) and style[mprop] != 'none' and style[
                        mprop][:5] == 'url(#':
                    marker_id = style[mprop][5:-1]
                    try:
                        old_mnode = self.xpathSingle(
                            '/svg:svg//svg:marker[@id="%s"]' % marker_id)
                        if not self.options.modify:
                            mnode = copy.deepcopy(old_mnode)
                        else:
                            mnode = old_mnode
                    except:
                        inkex.errormsg(
                            _("unable to locate marker: %s") % marker_id)
                        continue

                    new_id = self.uniqueId(marker_id, not self.options.modify)

                    style[mprop] = "url(#%s)" % new_id
                    mnode.set('id', new_id)
                    mnode.set(inkex.addNS('stockid', 'inkscape'), new_id)
                    defs.append(mnode)

                    children = mnode.xpath('.//*[@style]',
                                           namespaces=inkex.NSS)
                    for child in children:
                        cstyle = simplestyle.parseStyle(child.get('style'))
                        if ('stroke' in cstyle and cstyle['stroke'] != 'none'
                            ) or 'stroke' not in cstyle:
                            cstyle['stroke'] = stroke
                        if ('fill' in cstyle and cstyle['fill'] != 'none'
                            ) or 'fill' not in cstyle:
                            cstyle['fill'] = stroke
                        child.set('style', simplestyle.formatStyle(cstyle))
            node.set('style', simplestyle.formatStyle(style))
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tag == inkex.addNS('path', 'svg'):
                self.group = inkex.etree.SubElement(node.getparent(),
                                                    inkex.addNS('g', 'svg'))
                new = inkex.etree.SubElement(self.group,
                                             inkex.addNS('path', 'svg'))

                try:
                    t = node.get('transform')
                    self.group.set('transform', t)
                except:
                    pass

                s = simplestyle.parseStyle(node.get('style'))
                s['stroke-linecap'] = 'round'
                s['stroke-width'] = self.options.dotsize
                new.set('style', simplestyle.formatStyle(s))

                a = []
                p = simplepath.parsePath(node.get('d'))
                num = 1
                for cmd, params in p:
                    if cmd != 'Z':
                        a.append(['M', params[-2:]])
                        a.append(['L', params[-2:]])
                        self.addText(self.group, params[-2], params[-1], num)
                        num += 1
                new.set('d', simplepath.formatPath(a))
                node.clear()
Example #12
0
 def __call__(self, elem):
     style = elem.get("style")
     if style is None:
         return
     parsed = simplestyle.parseStyle(style)
     if "stroke" in parsed and parsed["stroke"] != "none":
         yield CheckerResult("element with stroke found", elem)
Example #13
0
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tagName == 'path':
                self.group = self.document.createElement('svg:g')
                node.parentNode.appendChild(self.group)
                new = self.document.createElement('svg:path')
                
                try:
                    t = node.attributes.getNamedItem('transform').value
                    self.group.setAttribute('transform', t)
                except AttributeError:
                    pass

                s = simplestyle.parseStyle(node.attributes.getNamedItem('style').value)
                s['stroke-linecap']='round'
                s['stroke-width']=self.options.dotsize
                new.setAttribute('style', simplestyle.formatStyle(s))

                a =[]
                p = simplepath.parsePath(node.attributes.getNamedItem('d').value)
                num = 1
                for cmd,params in p:
                    if cmd != 'Z':
                        a.append(['M',params[-2:]])
                        a.append(['L',params[-2:]])
                        self.addText(self.group,params[-2],params[-1],num)
                        num += 1
                new.setAttribute('d', simplepath.formatPath(a))
                self.group.appendChild(new)
                node.parentNode.removeChild(node)
Example #14
0
 def isGroupVisible(self, group):
     style = group.get('style')
     if style:
         style = simplestyle.parseStyle(style)
         if 'display' in style and style['display'] == 'none':
             return False
     return True
Example #15
0
 def isGroupVisible(self, group):
     style = group.get('style')
     if style:
         style = simplestyle.parseStyle(style)
         if 'display' in style and style['display'] == 'none':
             return False
     return True
Example #16
0
 def process_group(self, group):
     if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
         style = group.get('style')
         if style:
             style = simplestyle.parseStyle(style)
             if style.has_key('display'):
                 if style['display'] == 'none' and self.options.layer_option and self.options.layer_option=='visible':
                     return
         layer = group.get(inkex.addNS('label', 'inkscape'))
         if self.options.layer_name and self.options.layer_option and self.options.layer_option=='name' and not layer.lower() in self.options.layer_name:
             return
           
         layer = layer.replace(' ', '_')
         if layer in self.layers:
             self.layer = layer
     trans = group.get('transform')
     if trans:
         self.groupmat.append(simpletransform.composeTransform(self.groupmat[-1], simpletransform.parseTransform(trans)))
     for node in group:
         if node.tag == inkex.addNS('g','svg'):
             self.process_group(node)
         elif node.tag == inkex.addNS('use', 'svg'):
             self.process_clone(node)
         else:
             self.process_shape(node, self.groupmat[-1])
     if trans:
         self.groupmat.pop()
    def get_style(self, element):
        if element.get('style') is not None:
            return simplestyle.parseStyle(element.get('style'))
        else:
            return {}

        return style
    def process_group(self, group):
        if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
            style = group.get('style')
            if style:
                style = simplestyle.parseStyle(style)
                if style.has_key('display'):
                    if style[
                            'display'] == 'none' and self.options.layer_option and self.options.layer_option == 'visible':
                        return
            layer = group.get(inkex.addNS('label', 'inkscape'))
            if self.options.layer_name and self.options.layer_option and self.options.layer_option == 'name' and not layer.lower(
            ) in self.options.layer_name:
                return

            layer = layer.replace(' ', '_')
            if layer in self.layers:
                self.layer = layer
        trans = group.get('transform')
        if trans:
            self.groupmat.append(
                simpletransform.composeTransform(
                    self.groupmat[-1], simpletransform.parseTransform(trans)))
        for node in group:
            if node.tag == inkex.addNS('g', 'svg'):
                self.process_group(node)
            elif node.tag == inkex.addNS('use', 'svg'):
                self.process_clone(node)
            else:
                self.process_shape(node, self.groupmat[-1])
        if trans:
            self.groupmat.pop()
Example #19
0
    def labelFeature(self, node):
        if True:  #try:
            nodeStyle = simplestyle.parseStyle(node.attrib["style"])

            nodeColour, labelColour = \
                self.getNodeAndLabelColours(nodeStyle["fill"])
            nodeX, nodeY, nodeWidth, nodeHeight = \
                self.getNodeDimensions(node)

            parent = self.getParentNode(node)

            label = inkex.etree.SubElement(
                parent, inkex.addNS("text", "svg"), {
                    "x":
                    str(nodeX + (nodeWidth / 2)),
                    "y":
                    str(nodeY + (nodeHeight / 2)),
                    "dy":
                    "0.5em",
                    "style":
                    simplestyle.formatStyle({
                        "fill": labelColour,
                        "stroke": "none",
                        "text-anchor": "middle"
                    })
                })
            labelTextSpan = inkex.etree.SubElement(label,
                                                   inkex.addNS("tspan", "svg"),
                                                   {})
            labelTextSpan.text = nodeColour
Example #20
0
 def change_attribute(self, node, attribute):
     for key, value in attribute.items():
         if key == 'preserveAspectRatio':
             # set presentation attribute
             if value != "unset":
                 node.set(key, str(value))
             else:
                 if node.get(key):
                     del node.attrib[key]
         elif key == 'image-rendering':
             node_style = simplestyle.parseStyle(node.get('style'))
             if key not in node_style:
                 # set presentation attribute
                 if value != "unset":
                     node.set(key, str(value))
                 else:
                     if node.get(key):
                         del node.attrib[key]
             else:
                 # set style property
                 if value != "unset":
                     node_style[key] = str(value)
                 else:
                     del node_style[key]
                 node.set('style', simplestyle.formatStyle(node_style))
         else:
             pass
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tag == inkex.addNS('path','svg'):
                self.group = inkex.etree.SubElement(node.getparent(),inkex.addNS('g','svg'))
                new = inkex.etree.SubElement(self.group,inkex.addNS('path','svg'))
                
                try:
                    t = node.get('transform')
                    self.group.set('transform', t)
                except:
                    pass

                s = simplestyle.parseStyle(node.get('style'))
                s['stroke-linecap']='round'
                s['stroke-width']=self.options.dotsize
                new.set('style', simplestyle.formatStyle(s))

                a =[]
                p = simplepath.parsePath(node.get('d'))
                num = 1
                for cmd,params in p:
                    if cmd != 'Z':
                        a.append(['M',params[-2:]])
                        a.append(['L',params[-2:]])
                        self.addText(self.group,params[-2],params[-1],num)
                        num += 1
                new.set('d', simplepath.formatPath(a))
                node.clear()
Example #22
0
    def _get_fill(self, node):
        fill = {}
        fill['color'] = 'unset'
        fill['opacity'] = 1
        fill['visible'] = True

        #"fill", "fill-opacity", "opacity"
        styles = simplestyle.parseStyle(node.get("style"))
        color = node.get('fill', None)
        if (color is None):
            if ("fill" in styles):
                color = styles["fill"]
        if (color != None and color != 'none' and color != ''):
            fill['color'] = color

        fill_opacity = node.get('fill-opacity', 1)
        if (fill_opacity is 1):
            if ("fill-opacity" in styles):
                try:
                    fill_opacity = float(styles["fill-opacity"])
                except ValueError:
                    pass

        opacity = node.get('opacity', 1)
        if (opacity is 1):
            if ("opacity" in styles):
                try:
                    opacity = float(styles["opacity"])
                except ValueError:
                    pass

        fill['opacity'] = min(opacity, fill_opacity)
        fill['visible'] = fill['color'] is not None and fill['opacity'] > 0
        return fill
Example #23
0
    def split_letters(self, node):
        """Returns a list of letters"""

        letters = []
        
        words = self.split_words(node)
        if not words:
            return letters

        for word in words:
            
            x = float(word.get("x"))
            y = word.get("y")
           
            #gets the font size. If element doesn't have a style attribute, it assumes font-size = 12px
            try:
                import simplestyle
                fontsize = simplestyle.parseStyle(word.get("style"))["font-size"]
            except:
                fontsize = "12px"
            fs = self.unittouu(fontsize)

            #for each letter in element string
            for letter in word[0].text:
                tspan = inkex.etree.Element(inkex.addNS("tspan", "svg"))
                tspan.text = letter

                text = inkex.etree.Element(inkex.addNS("text", "svg"), node.attrib)
                text.set("x", str(x))
                text.set("y", str(y))
                x += fs
                
                text.append(tspan)
                letters.append(text)
        return letters
    def process_group(self, group):
        style = group.get('style')
        if style:
            style = simplestyle.parseStyle(style)

        if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
            if style:
                if style.has_key('display'):
                    if style['display'] == 'none' and self.visibleLayers:
                        return

        #stack the style of each group
        prevstyle = self.groupstyle.copy()
        if style:
            self.groupstyle.update(style)

        trans = group.get('transform')
        if trans:
            self.groupmat.append(
                simpletransform.composeTransform(
                    self.groupmat[-1], simpletransform.parseTransform(trans)))
        for node in group:
            if node.tag == inkex.addNS('g', 'svg'):
                self.process_group(node)
            elif node.tag == inkex.addNS('use', 'svg'):
                self.process_clone(node)
            else:
                self.process_shape(node, self.groupmat[-1])
        if trans:
            self.groupmat.pop()

        #pop the current group style
        self.groupstyle = prevstyle
Example #25
0
    def setGradient(self, href):
        try:
            g = self.svg.xpath("//*[@id='%s']" % href, namespaces=inkex.NSS)[0]
        except:
            return

        if g.get("r"):
            cx = float(g.get("cx"))
            cy = float(g.get("cy"))
            r = float(g.get("r"))
            self.createRadialGradient(href, cx, cy, r, cx, cy, r)
        else:
            x1 = float(g.get("x1"))
            y1 = float(g.get("y1"))
            x2 = float(g.get("x2"))
            y2 = float(g.get("y2"))
            self.createLinearGradient(href, x1, y1, x2, y2)

        #get gradient color stops
        gstops = g.get(inkex.addNS("href", "xlink"))
        gstops = self.svg.xpath("//svg:linearGradient[@id='%s']" % gstops[1:], namespaces=inkex.NSS)[0]
        for stop in gstops:
            style = simplestyle.parseStyle(stop.get("style"))
            stop_color = style["stop-color"]
            opacity = style["stop-opacity"]
            color = self.getColor(stop_color, opacity)
            pos = float(stop.get("offset"))
            self.addColorStop(href, pos, color)
        return href
Example #26
0
    def process_group(self, group):
        if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
            style = group.get('style')
            if style:
                style = simplestyle.parseStyle(style)
                if style.has_key('display'):
                    if style['display'] == 'none':
                        return
            layer = group.get(inkex.addNS('label', 'inkscape'))

            layer = layer.replace(' ', '_')
            if layer in self.layers:
                self.layer = layer
        trans = group.get('transform')
        if trans:
            self.groupmat.append(
                simpletransform.composeTransform(
                    self.groupmat[-1], simpletransform.parseTransform(trans)))
        for node in group:
            if node.tag == inkex.addNS('g', 'svg'):
                self.process_group(node)
            elif node.tag == inkex.addNS('use', 'svg'):
                self.process_clone(node)
            elif node.tag == inkex.addNS('defs', 'svg'):
                for sub in node:
                    if sub.tag == inkex.addNS('style', 'svg'):
                        self.parse_css(sub.text)
            else:
                self.process_shape(node, self.groupmat[-1])
        if trans:
            self.groupmat.pop()
Example #27
0
 def change_attribute(self, node, attribute):
     for key, value in attribute.items():
         if key == 'preserveAspectRatio':
             # set presentation attribute
             if value != "unset":
                 node.set(key, str(value))
             else:
                 if node.get(key):
                     del node.attrib[key]
         elif key == 'image-rendering':
             node_style = simplestyle.parseStyle(node.get('style'))
             if key not in node_style:
                 # set presentation attribute
                 if value != "unset":
                     node.set(key, str(value))
                 else:
                     if node.get(key):
                         del node.attrib[key]
             else:
                 # set style property
                 if value != "unset":
                     node_style[key] = str(value)
                 else:
                     del node_style[key]
                 node.set('style', simplestyle.formatStyle(node_style))
         else:
             pass
Example #28
0
   def plotPath(self, node, matTransform):
      """ Plot the path while applying the transformation defined by the matrix matTransform. """

      filledPath = (simplestyle.parseStyle(node.get("style")).get("fill", "none") != "none")

      # Plan: Turn this path into a cubicsuperpath (list of beziers)...
      d = node.get("d")
      if len(simplepath.parsePath(d)) == 0:
         return
      p = cubicsuperpath.parsePath(d)

      # ... and apply the transformation to each point.
      simpletransform.applyTransformToPath(matTransform, p)

      # p is now a list of lists of cubic beziers [cp1, cp2, endp]
      # where the start-point is the last point of the previous segment.
      # For some reason the inkscape extensions uses csp[1] as the coordinates of each point,
      # but that makes it seem like they are using control point 2 as line points.
      # Maybe that is a side-effect of the CSP subdivion process? TODO
      realPoints = []
      for sp in p:
         cspsubdiv.subdiv(sp, self.smoothness)
         for csp in sp:
            realPoints.append( (csp[1][0], csp[1][1]) )

      self.rawObjects.append( (filledPath, realPoints) )
def fix_font_size(node, mode='unset'):
    """Fix font size (copy to inner, unset for outer style)."""
    prop = 'font-size'
    fontsize = css_strut(node)[prop]
    # inner style
    inner = False
    for child in node.iterdescendants(tag=inkex.etree.Element):
        cdict = simplestyle.parseStyle(child.get('style'))
        if is_tspan(child) and is_line(child):
            # regular text
            inner = True
            if prop not in cdict and fontsize is not None:
                cdict[prop] = fontsize
                child.set('style', simplestyle.formatStyle(cdict))
        elif is_flowpara(child) or is_flowdiv(child):
            # flowed text
            inner = True
            if prop not in cdict and fontsize is not None:
                cdict[prop] = fontsize
                child.set('style', simplestyle.formatStyle(cdict))
    # outer style
    if inner:
        # unset font-size
        if mode == 'unset':
            del_prop(node, prop)
        elif mode == 'zero':
            if is_flowroot(node):
                val = FONTSIZE_ZERO
            else:
                val = FONTSIZE_ZERO
            update_prop(node, prop, val)
        else:
            pass
Example #30
0
    def process_group(self, group):
        ##############################################
        ### Get color set at group level
        stroke_group = group.get('stroke')
        ##############################################
        ### Handle 'style' data
        style = group.get('style')
        if style:
            declarations = style.split(';')
            for i, decl in enumerate(declarations):
                parts = decl.split(':', 2)
                if len(parts) == 2:
                    (prop, val) = parts
                    prop = prop.strip().lower()
                    if prop == 'stroke':
                        stroke_group = val.strip()
                    if prop == 'display' and val == "none":
                        #group display is 'none' return without processing group
                        return
        ##############################################

        if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
            style = group.get('style')
            if style:
                style = simplestyle.parseStyle(style)
                if 'display' in style:
                    if style['display'] == 'none':
                        #layer display is 'none' return without processing layer
                        return
            layer = group.get(inkex.addNS('label', 'inkscape'))

            layer = layer.replace(' ', '_')
            if layer in self.layers:
                self.layer = layer
        trans = group.get('transform')
        if trans:
            self.groupmat.append(
                simpletransform.composeTransform(
                    self.groupmat[-1], simpletransform.parseTransform(trans)))
        for node in group:
            if node.tag == inkex.addNS('g', 'svg') or node.tag == inkex.addNS(
                    'switch', 'svg'):
                self.process_group(node)
            elif node.tag == inkex.addNS('use', 'svg'):
                self.process_clone(node)

            elif node.tag == inkex.addNS('style', 'svg'):
                if node.get('type') == "text/css":
                    self.parse_css(node.text)

            elif node.tag == inkex.addNS('defs', 'svg'):
                for sub in node:
                    if sub.tag == inkex.addNS('style', 'svg'):
                        self.parse_css(sub.text)
            else:
                self.process_shape(node,
                                   self.groupmat[-1],
                                   group_stroke=stroke_group)
        if trans:
            self.groupmat.pop()
def fix_line_spacing(node, lineheight_zero=LINEHEIGHT_ZERO):
    """Fix line spacing (copy to inner, zero on outer style)."""
    prop = 'line-height'
    lineheight = css_strut(node)[prop]
    # inner style
    inner = False
    for child in node.iterdescendants(tag=inkex.etree.Element):
        cdict = simplestyle.parseStyle(child.get('style'))
        if is_tspan(child) and is_line(child):
            inner = True
            # regular text
            if prop not in cdict:
                cdict[prop] = lineheight
                child.set('style', simplestyle.formatStyle(cdict))
        elif is_flowpara(child) or is_flowdiv(child):
            inner = True
            # flowed text
            if prop not in cdict:
                cdict[prop] = lineheight
                child.set('style', simplestyle.formatStyle(cdict))
    # outer style
    if inner:
        # inkex.debug(lineheight_zero)
        if is_flowroot(node):
            # val = '0.01%'  # workaround for some fonts in flowed text
            val = lineheight_zero
        else:
            val = lineheight_zero
        update_prop(node, prop, val)
def fix_font_name(node, debug=False):
    """Fix generic font names (sans-serif, serif, monospace)."""
    prop = 'font-family'
    ink_prop = '-inkscape-font-specification'
    # inner style
    for child in node.iterchildren(tag=inkex.etree.Element):
        fix_font_name(child, debug)
    # outer style
    if prop in node.attrib:
        name = node.get(prop)
        if name in FONTFAMILY_GENERIC:
            node.set(prop, FONTFAMILY_GENERIC[name])
    pdict = simplestyle.parseStyle(node.get('style'))
    if prop in pdict:
        name = pdict[prop]
        if name in FONTFAMILY_GENERIC:
            pdict[prop] = FONTFAMILY_GENERIC[name]
            node.set('style', simplestyle.formatStyle(pdict))
    if ink_prop in pdict:
        if debug:
            inkex.debug(pdict[ink_prop])
        ink_val = pdict[ink_prop].strip("'").split()
        name = ink_val[0]
        if name in FONTFAMILY_GENERIC:
            if len(ink_val) > 1:
                ink_val[0] = FONTFAMILY_GENERIC[name]
                pdict[ink_prop] = "'" + ' '.join(ink_val) + "'"
            elif len(ink_val):
                pdict[ink_prop] = FONTFAMILY_GENERIC[name]
            node.set('style', simplestyle.formatStyle(pdict))
Example #33
0
    def effect(self):
        # get number of digits
        prec = int(self.options.precision)
        total = 0
        stotal = 0
        totals = {}
        # loop over all selected paths
        for node in self.document.getroot().iterdescendants():
            #path = "*"
            #for node in self.document.xpath(path, namespaces=inkex.NSS):
            if node.tag == inkex.addNS('path', 'svg'):
                id = node.get('id')
                self.group = inkex.etree.SubElement(node.getparent(),
                                                    inkex.addNS('text', 'svg'))
                t = node.get('transform')
                #inkex.debug(node.get("style"))
                d = node.get('d')
                if not ("stroke" in simplestyle.parseStyle(node.get("style"))
                        and len(simplepath.parsePath(d))):
                    continue
                stroke = simplestyle.parseStyle(node.get("style"))["stroke"]
                a = []
                p = cubicsuperpath.parsePath(node.get('d'))
                num = 1
                factor = 1.0 / inkex.unittouu('1' + self.options.unit)
                if self.options.type == "length":
                    slengths, stotal = csplength(p)
                else:
                    stotal, x0, y0 = csparea(p)
                    stotal *= factor * self.options.scale
                total += stotal
                if stroke in totals:
                    totals[stroke] += stotal
                else:
                    totals[stroke] = stotal
                # Format the length as string

        for key in totals:
            lenstr = locale.format("%(len)25." + str(prec) + "f", {
                'len':
                round(totals[key] * factor * self.options.scale, prec)
            }).strip()
            val = key
            for color in simplestyle.svgcolors.keys():
                if simplestyle.svgcolors.get(color) == key:
                    val = color
            inkex.debug(val + ":\t" + lenstr + "\t" + self.options.unit)
    def _get_color(self, color):
        """Retrieve and parse an inkscape color for use in android.
        
        Return a string "#RRGGBB", or None if not understood.  If inkscape color
        is a gradient, attempt to use one of the gradient colors.
        
        Required arguments:
        color -- string, inkscape color (from "style" attribute)
        """
        if color.startswith('#'):
            # already in the correct format
            return color
        elif color == 'none':
            # no color defined, transparent - we'll rely on the opacity attributes instead
            return None
        elif color.startswith('url(#') and color.endswith(')'):
            # parse ID to check for a gradient
            id = color[5:-1]
            if id.startswith('linearGradient') or id.startswith(
                    'radialGradient'):
                doc = self.document

                # find defined gradient
                prefix_terms = []
                prefix_terms.append(inkex.addNS('defs', 'svg'))
                prefix_terms.append('/')
                prefix_terms.append('*[@id=\'')
                prefix = ''.join(prefix_terms)
                suffix = '\']'
                gradient = doc.find(prefix + id + suffix)

                # get link to the other gradient definition (with the colors defined)
                link_attr = inkex.addNS('href', 'xlink')
                if gradient is None or link_attr not in gradient.attrib:
                    return None
                link_id = gradient.get(link_attr)
                if link_id.startswith('#'):
                    link_id = link_id[1:]

                # get stop element
                suffix_terms = []
                suffix_terms.append('\']/')
                suffix_terms.append(inkex.addNS('stop', 'svg'))
                suffix = ''.join(suffix_terms)
                stop = doc.find(prefix + link_id + suffix)

                # parse style attribute of stop element
                if stop is None or 'style' not in stop.attrib:
                    return None
                style = ss.parseStyle(stop.get('style'))

                if 'stop-color' not in style:
                    return None

                # recursively attempt to parse the found color
                return self._get_color(style['stop-color'])

        # color wasn't understood
        return None
    def effect(self):
        object2path.ObjectToPath.effect(self)

        transformMatrix = [[1,0,0],[0,1,0]]
        dims = self.determine_dims(transformMatrix)

        [x,y,X,Y] = dims
        width = X - x
        height = Y - y

        # Longest side is vertical
        if width > height:
            scale = 480.0 / height
            if scale * width > 999.0:
                inkex.errormsg("Plot area is to large (%f > 999)." % scale*height)
                exit()
            transformMatrix = parseTransform('translate(%f,%f)' % (-x,-y))
            transformMatrix = composeTransform(parseTransform('rotate(-90)'), transformMatrix)
            transformMatrix = composeTransform(parseTransform('scale(%f,%f)' % (scale,scale)), transformMatrix)
        else:
            scale = 480.0 / width
            if scale * height > 999.0:
                inkex.errormsg("Plot area is to large (%f > 999)." % scale*height)
                exit()
            transformMatrix = parseTransform('translate(%f,%f)' % (-x,-y))
            transformMatrix = composeTransform(parseTransform('rotate(180)'), transformMatrix)
            transformMatrix = composeTransform(parseTransform('translate(%f,0)' % width), transformMatrix)
            transformMatrix = composeTransform(parseTransform('scale(%f,%f)' % (-scale,scale)), transformMatrix)
            transformMatrix = composeTransform(parseTransform('translate(480,0)'), transformMatrix)

        paths = []
        for [path, node] in self.processPaths(transformMatrix):
            color = (0, 0, 0)
            style = node.get('style')
            if style:
                style = simplestyle.parseStyle(style)
                if 'stroke' in style:
                    if style['stroke'] and style['stroke'] != 'none':
                        color = simplestyle.parseColor(style['stroke'])
            points = []
            for point in self.processPath(path):
                points.append(point)
            paths.append({'color':color, 'points':points})

        dims = self.determine_dims(transformMatrix)
        if self.options.debug:
            print >>sys.stderr, "VC1520 debug info"
            print >>sys.stderr, "-----------------"
            print >>sys.stderr, "plot area: minX:%d, minY:%d, maxX:%d, maxY:%d" % tuple(dims)
            print >>sys.stderr, "nr paths: %d" % len(paths)
            i = 0
            print >>sys.stderr, "path;color;points"
            for path in paths:
                print >>sys.stderr, "%d;%s;%d" % (i,self.find_color(path['color']),len(path['points']))
                i += 1
            for path in paths:
                print >>sys.stderr, path
        else:
            self.plot(paths, dims[1])
def checkStyle(node):
    if node.hasAttributes():
        sa=node.getAttribute('style')
        if sa!='':
            styles=simplestyle.parseStyle(sa)
            for c in range(len(colortags)):
                if colortags[c] in styles.keys():
                    addColor(styles[colortags[c]])
def checkStyle(node):
    if hasattr(node, "hasAttributes") and node.hasAttributes():
        sa = node.getAttribute("style")
        if sa != "":
            styles = simplestyle.parseStyle(sa)
            for c in range(len(colortags)):
                if colortags[c] in styles.keys():
                    addColor(styles[colortags[c]])
Example #38
0
 def get_style(self, element):
     element_style = element.get('style')
     if element_style is not None:
         if hasattr(inkex, 'Style') and hasattr(inkex.Style, 'parse_str'):
             return dict(inkex.Style.parse_str(element_style))  # >= 1.0
         else:
             return simplestyle.parseStyle(element_style)  # inkscape < 1.0
     return {}
def checkStyle(node):
    if hasattr(node, "hasAttributes") and node.hasAttributes():
        sa = node.getAttribute('style')
        if sa != '':
            styles = simplestyle.parseStyle(sa)
            for c in range(len(colortags)):
                if colortags[c] in styles.keys():
                    addColor(styles[colortags[c]])
Example #40
0
 def get_style(self, style_name, default=None):
     style = simplestyle.parseStyle(self.node.get("style"))
     if (style_name not in style):
         return default
     value = style[style_name]
     if value == 'none':
         return None
     return value
def del_prop(node, prop):
    """Delete attribute or style property from node."""
    if prop in node.attrib:
        del node.attrib[prop]
    pdict = simplestyle.parseStyle(node.get('style'))
    if prop in pdict:
        del pdict[prop]
        node.set('style', simplestyle.formatStyle(pdict))
Example #42
0
    def recursiveFuseTransform(self, node, transf=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]):
        transf = composeTransform(transf, parseTransform(node.get("transform", None)))

        if 'transform' in node.attrib:
            del node.attrib['transform']

        if 'style' in node.attrib:
            style = node.attrib.get('style')
            style = simplestyle.parseStyle(style)
            update = False

            if 'stroke-width' in style:
                try:
                    stroke_width = self.unittouu(style.get('stroke-width').strip())
                    # pixelsnap ext assumes scaling is similar in x and y
                    # and uses the x scale...
                    # let's try to be a bit smarter
                    stroke_width *= math.sqrt(transf[0][0]**2 + transf[1][1]**2)
                    style['stroke-width'] = str(stroke_width)
                    update = True
                except AttributeError:
                    pass

            if update:
                style = simplestyle.formatStyle(style)
                node.attrib['style'] = style

        node = ApplyTransform.objectToPath(node)

        if 'd' in node.attrib:
            d = node.get('d')
            p = cubicsuperpath.parsePath(d)
            applyTransformToPath(transf, p)
            node.set('d', cubicsuperpath.formatPath(p))

        elif node.tag in [inkex.addNS('polygon', 'svg'),
                          inkex.addNS('polyline', 'svg')]:
            points = node.get('points')
            points = points.strip().split(' ')
            for k,p in enumerate(points):
                if ',' in p:
                    p = p.split(',')
                    p = [float(p[0]),float(p[1])]
                    applyTransformToPoint(transf, p)
                    p = [str(p[0]),str(p[1])]
                    p = ','.join(p)
                    points[k] = p
            points = ' '.join(points)
            node.set('points', points)

        elif node.tag in [inkex.addNS('rect', 'svg'),
                          inkex.addNS('text', 'svg'),
                          inkex.addNS('image', 'svg'),
                          inkex.addNS('use', 'svg')]:
            node.set('transform', formatTransform(transf))

        for child in node.getchildren():
            self.recursiveFuseTransform(child, transf)
Example #43
0
 def process_shape(self, node, mat):
     rgb = (0, 0, 0)  # stroke color
     fillcolor = None  # fill color
     stroke = 1  # pen width in printer pixels
     # Very NB : If the pen width is greater than 1 then the output will Not be a vector output !
     style = node.get('style')
     if style:
         style = simplestyle.parseStyle(style)
         if style.has_key('stroke'):
             if style['stroke'] and style['stroke'] != 'none' and style[
                     'stroke'][0:3] != 'url':
                 rgb = simplestyle.parseColor(style['stroke'])
         if style.has_key('stroke-width'):
             stroke = self.unittouu(
                 style['stroke-width']) / self.unittouu('1px')
             stroke = int(stroke * self.scale)
         if style.has_key('fill'):
             if style['fill'] and style['fill'] != 'none' and style['fill'][
                     0:3] != 'url':
                 fill = simplestyle.parseColor(style['fill'])
                 fillcolor = fill[0] + 256 * fill[1] + 256 * 256 * fill[2]
     color = rgb[0] + 256 * rgb[1] + 256 * 256 * rgb[2]
     if node.tag == inkex.addNS('path', 'svg'):
         d = node.get('d')
         if not d:
             return
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('rect', 'svg'):
         x = float(node.get('x'))
         y = float(node.get('y'))
         width = float(node.get('width'))
         height = float(node.get('height'))
         p = [[[x, y], [x, y], [x, y]]]
         p.append([[x + width, y], [x + width, y], [x + width, y]])
         p.append([[x + width, y + height], [x + width, y + height],
                   [x + width, y + height]])
         p.append([[x, y + height], [x, y + height], [x, y + height]])
         p.append([[x, y], [x, y], [x, y]])
         p = [p]
     else:
         return
     trans = node.get('transform')
     if trans:
         mat = simpletransform.composeTransform(
             mat, simpletransform.parseTransform(trans))
     simpletransform.applyTransformToPath(mat, p)
     hPen = mygdi.CreatePen(0, stroke, color)
     mygdi.SelectObject(self.hDC, hPen)
     self.emit_path(p)
     if fillcolor is not None:
         brush = LOGBRUSH(0, fillcolor, 0)
         hBrush = mygdi.CreateBrushIndirect(addressof(brush))
         mygdi.SelectObject(self.hDC, hBrush)
         mygdi.BeginPath(self.hDC)
         self.emit_path(p)
         mygdi.EndPath(self.hDC)
         mygdi.FillPath(self.hDC)
     return
Example #44
0
    def split_words(self, node):
        """Returns a list of words"""

        words = []

        # Function to recursively extract text
        def plain_str(elem):
            words = []
            if elem.text:
                words.append(elem.text)
            for n in elem:
                words.extend(plain_str(n))
                if n.tail:
                    words.append(n.tail)
            return words

        # if text has more than one line, iterates through elements
        lines = self.split_lines(node)
        if not lines:
            return words

        for line in lines:
            # gets the position of text node
            x = float(line.get("x"))
            y = line.get("y")

            # gets the font size. if element doesn't have a style attribute, it assumes font-size = 12px
            try:
                from simplestyle import parseStyle

                fontsize = parseStyle(line.get("style"))["font-size"]
            except:
                fontsize = "12px"
            fs = inkex.unittouu(fontsize)

            # extract and returns a list of words
            words_list = "".join(plain_str(line)).split()
            prev_len = 0

            # creates new text nodes for each string in words_list
            for word in words_list:
                tspan = inkex.etree.Element(inkex.addNS("tspan", "svg"))
                tspan.text = word

                text = inkex.etree.Element(inkex.addNS("text", "svg"), line.attrib)
                tspan.set(inkex.addNS("role", "sodipodi"), "line")

                # positioning new text elements
                x = x + prev_len * fs
                prev_len = len(word)
                text.set("x", str(x))
                text.set("y", str(y))

                text.append(tspan)
                words.append(text)

        return words
Example #45
0
    def split_lines(self, node):
        """Returns a list of lines"""

        lines = []
        count = 1

        for n in node:
            if not (n.tag == inkex.addNS("flowPara", "svg") or n.tag == inkex.addNS("tspan", "svg")):
                if n.tag == inkex.addNS("textPath", "svg"):
                    inkex.debug("This type of text element isn't supported. First remove text from path.")
                    break
                else:
                    continue

            text = inkex.etree.Element(inkex.addNS("text", "svg"), node.attrib)

            # handling flowed text nodes
            if node.tag == inkex.addNS("flowRoot", "svg"):
                try:
                    from simplestyle import parseStyle

                    fontsize = parseStyle(node.get("style"))["font-size"]
                except:
                    fontsize = "12px"
                fs = inkex.unittouu(fontsize)

                # selects the flowRegion's child (svg:rect) to get @X and @Y
                id = node.get("id")
                flowref = self.xpathSingle('/svg:svg//*[@id="%s"]/svg:flowRegion[1]' % id)[0]

                if flowref.tag == inkex.addNS("rect", "svg"):
                    text.set("x", flowref.get("x"))
                    text.set("y", str(float(flowref.get("y")) + fs * count))
                    count += 1
                else:
                    inkex.debug("This type of text element isn't supported. First unflow text.")
                    break

                # now let's convert flowPara into tspan
                tspan = inkex.etree.Element(inkex.addNS("tspan", "svg"))
                tspan.set(inkex.addNS("role", "sodipodi"), "line")
                tspan.text = n.text
                text.append(tspan)

            else:
                from copy import copy

                x = n.get("x") or node.get("x")
                y = n.get("y") or node.get("y")

                text.set("x", x)
                text.set("y", y)
                text.append(copy(n))

            lines.append(text)

        return lines
Example #46
0
    def split_words(self, node):
        """Returns a list of words"""

        words = []

        #Function to recursively extract text
        def plain_str(elem):
            words = []
            if elem.text:
                words.append(elem.text)
            for n in elem:
                words.extend(plain_str(n))
                if n.tail:
                    words.append(n.tail)
            return words

        #if text has more than one line, iterates through elements
        lines = self.split_lines(node)
        if not lines:
            return words

        for line in lines:
            #gets the position of text node
            x = float(line.get("x"))
            y = line.get("y")

            #gets the font size. if element doesn't have a style attribute, it assumes font-size = 12px
            try:
                from simplestyle import parseStyle
                fontsize = parseStyle(line.get("style"))["font-size"]
            except:
                fontsize = "12px"
            fs = inkex.unittouu(fontsize)

            #extract and returns a list of words
            words_list = "".join(plain_str(line)).split()
            prev_len = 0

            #creates new text nodes for each string in words_list
            for word in words_list:
                tspan = inkex.etree.Element(inkex.addNS("tspan", "svg"))
                tspan.text = word

                text = inkex.etree.Element(inkex.addNS("text", "svg"),
                                           line.attrib)
                tspan.set(inkex.addNS("role", "sodipodi"), "line")

                #positioning new text elements
                x = x + prev_len * fs
                prev_len = len(word)
                text.set("x", str(x))
                text.set("y", str(y))

                text.append(tspan)
                words.append(text)

        return words
 def effect(self):
     defs = self.xpathSingle('/svg:svg//svg:defs')
     if defs == None:
         defs = inkex.etree.SubElement(self.document.getroot(),inkex.addNS('defs','svg'))
     
     for id, node in self.selected.iteritems():
         mprops = ['marker','marker-start','marker-mid','marker-end']
         try:
             style = simplestyle.parseStyle(node.get('style'))
         except:
             inkex.errormsg(_("No style attribute found for id: %s") % id)
             continue
         
         stroke = style.get('stroke', '#000000')
         
         for mprop in mprops:
             if style.has_key(mprop) and style[mprop] != 'none'and style[mprop][:5] == 'url(#':
                 marker_id = style[mprop][5:-1]
                 try:
                     old_mnode = self.xpathSingle('/svg:svg//svg:marker[@id="%s"]' % marker_id)
                     if not self.options.modify:
                         mnode = copy.deepcopy(old_mnode)
                     else:
                         mnode = old_mnode
                 except:
                     inkex.errormsg(_("unable to locate marker: %s") % marker_id)
                     continue
                     
                 new_id = self.uniqueId(marker_id, not self.options.modify)
                 
                 style[mprop] = "url(#%s)" % new_id
                 mnode.set('id', new_id)
                 mnode.set(inkex.addNS('stockid','inkscape'), new_id)
                 defs.append(mnode)
                 
                 children = mnode.xpath('.//*[@style]', namespaces=inkex.NSS)
                 for child in children:
                     cstyle = simplestyle.parseStyle(child.get('style'))
                     if ('stroke' in cstyle and cstyle['stroke'] != 'none') or 'stroke' not in cstyle:
                         cstyle['stroke'] = stroke
                     if ('fill' in cstyle and cstyle['fill'] != 'none') or 'fill' not in cstyle:
                         cstyle['fill'] = stroke
                     child.set('style',simplestyle.formatStyle(cstyle))
         node.set('style',simplestyle.formatStyle(style))
    def effect(self):
        # get number of digits
        prec = int(self.options.precision)
        total = 0
        stotal = 0
        totals = {}
        # loop over all selected paths
        for node in self.document.getroot().iterdescendants():
            # path = "*"
            # for node in self.document.xpath(path, namespaces=inkex.NSS):
            if node.tag == inkex.addNS("path", "svg"):
                id = node.get("id")
                self.group = inkex.etree.SubElement(node.getparent(), inkex.addNS("text", "svg"))
                t = node.get("transform")
                # inkex.debug(node.get("style"))
                d = node.get("d")
                if not ("stroke" in simplestyle.parseStyle(node.get("style")) and len(simplepath.parsePath(d))):
                    continue
                stroke = simplestyle.parseStyle(node.get("style"))["stroke"]
                a = []
                p = cubicsuperpath.parsePath(node.get("d"))
                num = 1
                factor = 1.0 / inkex.unittouu("1" + self.options.unit)
                if self.options.type == "length":
                    slengths, stotal = csplength(p)
                else:
                    stotal, x0, y0 = csparea(p)
                    stotal *= factor * self.options.scale
                total += stotal
                if stroke in totals:
                    totals[stroke] += stotal
                else:
                    totals[stroke] = stotal
                # Format the length as string

        for key in totals:
            lenstr = locale.format(
                "%(len)25." + str(prec) + "f", {"len": round(totals[key] * factor * self.options.scale, prec)}
            ).strip()
            val = key
            for color in simplestyle.svgcolors.keys():
                if simplestyle.svgcolors.get(color) == key:
                    val = color
            inkex.debug(val + ":\t" + lenstr + "\t" + self.options.unit)
Example #49
0
    def style_path(self, node):
        style = simplestyle.parseStyle(node.get("style"))
        style['opacity'] = 1.0
        style['stroke-opacity'] = def_opacity
        style['stroke'] = def_color
        style['stroke-width'] = 5

        style['marker-start'] = "url(#inkslides-marker-start)"
        style['marker-mid'] = "url(#inkslides-marker)"
        style['marker-end'] = "url(#inkslides-marker-end)"
        node.set("style", simplestyle.formatStyle(style))
Example #50
0
 def modify_layer_style(self, layer, style):
     if (layer.attrib.has_key('style')):
         currentStyle = simplestyle.parseStyle(layer.attrib['style'])
         for k,v in style.items():
             if v == None:
                 if currentStyle.has_key(k):
                     del currentStyle[k]
             else:
                 currentStyle[k] = style[k]
         style = currentStyle
     layer.attrib['style'] = simplestyle.formatStyle(style)
Example #51
0
 def process_shape(self, node, mat):
     rgb = (0,0,0)                   # stroke color
     fillcolor = None                # fill color
     stroke = 1                      # pen width in printer pixels
     # Very NB : If the pen width is greater than 1 then the output will Not be a vector output !
     style = node.get('style')
     if style:
         style = simplestyle.parseStyle(style)
         if style.has_key('stroke'):
             if style['stroke'] and style['stroke'] != 'none' and style['stroke'][0:3] != 'url':
                 rgb = simplestyle.parseColor(style['stroke'])
         if style.has_key('stroke-width'):
             stroke = self.unittouu(style['stroke-width'])
             stroke = int(stroke*self.scale)
         if style.has_key('fill'):
             if style['fill'] and style['fill'] != 'none' and style['fill'][0:3] != 'url':
                 fill = simplestyle.parseColor(style['fill'])
                 fillcolor = fill[0] + 256*fill[1] + 256*256*fill[2]
     color = rgb[0] + 256*rgb[1] + 256*256*rgb[2]
     if node.tag == inkex.addNS('path','svg'):
         d = node.get('d')
         if not d:
             return
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('rect','svg'):
         x = float(node.get('x'))
         y = float(node.get('y'))
         width = float(node.get('width'))
         height = float(node.get('height'))
         p = [[[x, y],[x, y],[x, y]]]
         p.append([[x + width, y],[x + width, y],[x + width, y]])
         p.append([[x + width, y + height],[x + width, y + height],[x + width, y + height]])
         p.append([[x, y + height],[x, y + height],[x, y + height]])
         p.append([[x, y],[x, y],[x, y]])
         p = [p]
     else:
         return
     trans = node.get('transform')
     if trans:
         mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
     simpletransform.applyTransformToPath(mat, p)
     hPen = mygdi.CreatePen(0, stroke, color)
     mygdi.SelectObject(self.hDC, hPen)
     self.emit_path(p)
     if fillcolor is not None:
         brush = LOGBRUSH(0, fillcolor, 0)
         hBrush = mygdi.CreateBrushIndirect(addressof(brush))
         mygdi.SelectObject(self.hDC, hBrush)
         mygdi.BeginPath(self.hDC)
         self.emit_path(p)
         mygdi.EndPath(self.hDC)
         mygdi.FillPath(self.hDC)
     return
 def update_node_attrib(self, node, attrib_name, attribs_to_overwrite):
     """
     svg style is overloaded with a dictlike value:
     <rect
    style="opacity:0;fill:#eeeeec;fill-opacity:1;stroke:none;stroke-width:4.00099993;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;display:inline"
     """
     style = node.attrib[attrib_name]
     value_dict = simplestyle.parseStyle(style)
     for key, value in attribs_to_overwrite.items():
         value_dict[key] = value
     new_value = simplestyle.formatStyle(value_dict)
     node.attrib[attrib_name] = new_value
def layerDisplay(layer, displayed):
    if "style" in layer.attrib:
        style = simplestyle.parseStyle(layer.attrib["style"])
    else:
        style = {}

    if displayed:
        style["display"]="inline"
    else:
        style["display"]="none"

    layer.attrib["style"] = simplestyle.formatStyle(style)
 def _ungroup(self, node):
     node_parent = node.getparent()
     node_index = list(node_parent).index(node)
     node_style = simplestyle.parseStyle(node.get("style"))
     node_transform = simpletransform.parseTransform(node.get("transform"))
     node_clippathurl = node.get('clip-path')
     for c in reversed(list(node)):
         self._merge_transform(c, node_transform)
         self._merge_style(c, node_style)
         self._merge_clippath(c, node_clippathurl)
         node_parent.insert(node_index, c)
     node_parent.remove(node)
Example #55
0
    def expandGroupsUnlinkClones(self,aList,transferTransform=True,doReplace=True):
        for id in aList.keys()[:]:     
            node=aList[id]
            if node.tag == inkex.addNS('g','svg') or node.tag=='g':
                self.expandGroups(aList,transferTransform)
                self.expandGroupsUnlinkClones(aList,transferTransform,doReplace)
                #Hum... not very efficient if there are many clones of groups...

            elif node.tag == inkex.addNS('use','svg') or node.tag=='use':
                refnode=self.refNode(node)
                newnode=self.unlinkClone(node,doReplace)
                del aList[id]

                style = simplestyle.parseStyle(node.get('style') or "")
                refstyle=simplestyle.parseStyle(refnode.get('style') or "")
                style.update(refstyle)
                newnode.set('style',simplestyle.formatStyle(style))

                newid=newnode.get('id')
                aList.update(self.expandGroupsUnlinkClones({newid:newnode},transferTransform,doReplace))
        return aList
 def process_shape(self, node, mat):
     rgb = (0,0,0)
     style = node.get('style')
     if style:
         style = simplestyle.parseStyle(style)
         if style.has_key('stroke'):
             if style['stroke'] and style['stroke'] != 'none' and style['stroke'][0:3] != 'url':
                 rgb = simplestyle.parseColor(style['stroke'])
     hsl = coloreffect.ColorEffect.rgb_to_hsl(coloreffect.ColorEffect(),rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0)
     self.closed = 0                                 # only for LWPOLYLINE
     self.color = 7                                  # default is black
     if hsl[2]:
         #self.color = 1 + (int(6*hsl[0] + 0.5) % 6)  # use 6 hues
         self.color = 1 + (int(10*hsl[0] + 0.5) % 10)  # use 6 hues
     if node.tag == inkex.addNS('path','svg'):
         d = node.get('d')
         if not d:
             return
         if (d[-1] == 'z' or d[-1] == 'Z'):
             self.closed = 1
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('rect','svg'):
         self.closed = 1
         x = float(node.get('x'))
         y = float(node.get('y'))
         width = float(node.get('width'))
         height = float(node.get('height'))
         p = [[[x, y],[x, y],[x, y]]]
         p.append([[x + width, y],[x + width, y],[x + width, y]])
         p.append([[x + width, y + height],[x + width, y + height],[x + width, y + height]])
         p.append([[x, y + height],[x, y + height],[x, y + height]])
         p.append([[x, y],[x, y],[x, y]])
         p = [p]
     else:
         return
     trans = node.get('transform')
     if trans:
         mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
     simpletransform.applyTransformToPath(mat, p)
     for sub in p:
         for i in range(len(sub)-1):
             s = sub[i]
             e = sub[i+1]
             if s[1] == s[2] and e[0] == e[1]:
                 if (self.options.POLY == 'true'):
                     self.LWPOLY_line([s[1],e[1]])
                 else:
                     self.dxf_line([s[1],e[1]])
             elif (self.options.ROBO == 'true'):
                 self.ROBO_spline([s[1],s[2],e[0],e[1]])
             else:
                 self.dxf_spline([s[1],s[2],e[0],e[1]])
Example #57
0
 def setStyle(self, ctx, node):
     """Translates style properties names into method calls"""
     style = simplestyle.parseStyle(node.get("style"))
     #remove any trailing space in dict keys/values
     style = dict([(str.strip(k), str.strip(v)) for k,v in style.iteritems()])
     ctx.style = style
     for key in style:
         tmp_list = map(str.capitalize, key.split("-"))
         method = "set" + "".join(tmp_list)
         if hasattr(ctx, method) and style[key] != "none":
             getattr(ctx, method)(style[key])
     #saves style to compare in next iteration
     ctx.styleCache = style
Example #58
0
    def groupToPath(self,node,doReplace=True):
        if node.tag == inkex.addNS('g','svg'):
            newNode = inkex.etree.SubElement(self.current_layer,inkex.addNS('path','svg'))    

            newstyle = simplestyle.parseStyle(node.get('style') or "")
            newp = []
            for child in node:
                childstyle = simplestyle.parseStyle(child.get('style') or "")
                childstyle.update(newstyle)
                newstyle.update(childstyle)
                childAsPath = self.objectToPath(child,False)
                newp += cubicsuperpath.parsePath(childAsPath.get('d'))
            newNode.set('d',cubicsuperpath.formatPath(newp))
            newNode.set('style',simplestyle.formatStyle(newstyle))

            self.current_layer.remove(newNode)
            if doReplace:
                parent=node.getparent()
                parent.insert(parent.index(node),newNode)
                parent.remove(node)

            return newNode
        else:
            raise AssertionError