Пример #1
0
def inkscape(hpgl, svg, inkex):
    layer = inkex.etree.SubElement(svg, 'g')
    layer.set(inkex.addNS('label', 'inkscape'), 'InkCut Preview Layer')
    layer.set(inkex.addNS('groupmode', 'inkscape'), 'layer')
    spPU = [['M', [0, 0]]]
    spPD = []
    for c in hpgl.split(';'):
        if c[:2] == "PU":
            p = map(int, c[2:].split(','))
            spPD.append(['M', p])
            spPU.append(['L', p])
        elif c[:2] == "PD":
            p = map(int, c[2:].split(','))
            spPU.append(['M', p])
            spPD.append(['L', p])

    pu = inkex.etree.Element(inkex.addNS('path', 'svg'))

    simplepath.scalePath(spPU, 0.088582677, -0.088582677)
    simplepath.translatePath(spPU, 0, float(svg.get('height')))

    style = {'fill': 'none', 'stroke-opacity': '.8', 'stroke': '#116AAB'}
    pu.set('style', simplestyle.formatStyle(style))
    pu.set('d', simplepath.formatPath(spPU))

    pd = inkex.etree.Element(inkex.addNS('path', 'svg'))

    style = {'fill': 'none', 'stroke-opacity': '.8', 'stroke': '#AB3011'}
    pd.set('style', simplestyle.formatStyle(style))
    pd.set('d', simplepath.formatPath(spPD))

    # Connect elements together.
    layer.append(pu)
    layer.append(pd)
Пример #2
0
def inkscape(hpgl,svg,inkex):
	layer = inkex.etree.SubElement(svg, 'g')
	layer.set(inkex.addNS('label', 'inkscape'), 'InkCut Preview Layer')
	layer.set(inkex.addNS('groupmode', 'inkscape'), 'layer')
	spPU = [['M',[0,0]]]
	spPD = []
	for c in hpgl.split(';'):
		if c[:2] == "PU":
			p = map(int,c[2:].split(','))
			spPD.append(['M',p])
			spPU.append(['L',p])
		elif c[:2] == "PD":
			p = map(int,c[2:].split(','))
			spPU.append(['M',p])
			spPD.append(['L',p])		
	
	pu = inkex.etree.Element(inkex.addNS('path','svg'))
	
	simplepath.scalePath(spPU,0.088582677,-0.088582677)
	simplepath.translatePath(spPU,0,float(svg.get('height')))
	
	style = {'fill' : 'none','stroke-opacity': '.8','stroke':'#116AAB'}
	pu.set('style', simplestyle.formatStyle(style))
	pu.set('d',simplepath.formatPath(spPU))
	
	
	pd = inkex.etree.Element(inkex.addNS('path','svg'))
	
	style = {'fill' : 'none','stroke-opacity': '.8','stroke':'#AB3011'}
	pd.set('style', simplestyle.formatStyle(style))
	pd.set('d',simplepath.formatPath(spPD))
	
	# Connect elements together.
	layer.append(pu)
	layer.append(pd)
    def effect(self):
        paths = []
        for id, node in self.selected.iteritems():
            if node.tag == '{http://www.w3.org/2000/svg}path':
                paths.append(node)
                if len(paths) == 2:
                    break
        else:
            sys.stderr.write('Need 2 paths selected\n')
            return

        pts = [cubicsuperpath.parsePath(paths[i].get('d')) for i in (0, 1)]

        for i in (0, 1):
            if 'transform' in paths[i].keys():
                trans = paths[i].get('transform')
                trans = simpletransform.parseTransform(trans)
                simpletransform.applyTransformToPath(trans, pts[i])

        verts = []
        for i in range(0, min(map(len, pts))):
            comp = []
            for j in range(0, min(len(pts[0][i]), len(pts[1][i]))):
                comp.append([pts[0][i][j][1][-2:], pts[1][i][j][1][-2:]])
            verts.append(comp)

        if self.options.mode.lower() == 'lines':
            line = []
            for comp in verts:
                for n, v in enumerate(comp):
                    line += [('M', v[0])]
                    line += [('L', v[1])]
            ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')
            paths[0].xpath('..')[0].append(ele)
            ele.set('d', simplepath.formatPath(line))
            ele.set(
                'style',
                'fill:none;stroke:#000000;stroke-opacity:1;stroke-width:1;')
        elif self.options.mode.lower() == 'polygons':
            g = inkex.etree.Element('{http://www.w3.org/2000/svg}g')
            g.set(
                'style',
                'fill:#000000;stroke:#000000;fill-opacity:0.3;stroke-width:2;stroke-opacity:0.6;'
            )
            paths[0].xpath('..')[0].append(g)
            for comp in verts:
                for n, v in enumerate(comp):
                    nn = n + 1
                    if nn == len(comp): nn = 0
                    line = []
                    line += [('M', comp[n][0])]
                    line += [('L', comp[n][1])]
                    line += [('L', comp[nn][1])]
                    line += [('L', comp[nn][0])]
                    line += [('L', comp[n][0])]
                    ele = inkex.etree.Element(
                        '{http://www.w3.org/2000/svg}path')
                    g.append(ele)
                    ele.set('d', simplepath.formatPath(line))
    def effect(self):
        paths = []
        for id, node in self.selected.iteritems():
            if node.tag == '{http://www.w3.org/2000/svg}path':
                paths.append(node)
                if len(paths) == 2:
                    break
        else:
            sys.stderr.write('Need 2 paths selected\n')
            return


        pts = [cubicsuperpath.parsePath(paths[i].get('d'))
               for i in (0,1)]

        for i in (0,1):
            if 'transform' in paths[i].keys():
                trans = paths[i].get('transform')
                trans = simpletransform.parseTransform(trans)
                simpletransform.applyTransformToPath(trans, pts[i])

        verts = []
        for i in range(0, min(map(len, pts))):
            comp = []
            for j in range(0, min(len(pts[0][i]), len(pts[1][i]))):
                comp.append([pts[0][i][j][1][-2:], pts[1][i][j][1][-2:]])
            verts.append(comp)

        if self.options.mode.lower() == 'lines':
            line = []
            for comp in verts:
                for n,v in enumerate(comp):
                  line += [('M', v[0])]
                  line += [('L', v[1])]
            ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')
            paths[0].xpath('..')[0].append(ele)
            ele.set('d', simplepath.formatPath(line))
            ele.set('style', 'fill:none;stroke:#000000;stroke-opacity:1;stroke-width:1;')
        elif self.options.mode.lower() == 'polygons':
            g = inkex.etree.Element('{http://www.w3.org/2000/svg}g')
            g.set('style', 'fill:#000000;stroke:#000000;fill-opacity:0.3;stroke-width:2;stroke-opacity:0.6;')   
            paths[0].xpath('..')[0].append(g)
            for comp in verts:
                for n,v in enumerate(comp):
                    nn = n+1
                    if nn == len(comp): nn = 0
                    line = []
                    line += [('M', comp[n][0])]
                    line += [('L', comp[n][1])]
                    line += [('L', comp[nn][1])]
                    line += [('L', comp[nn][0])]
                    line += [('L', comp[n][0])]
                    ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')
                    g.append(ele)
                    ele.set('d', simplepath.formatPath(line))
Пример #5
0
    def effect(self):
        paths = []
        for id, node in self.selected.iteritems():
            if node.tag == "{http://www.w3.org/2000/svg}path":
                paths.append(node)
                if len(paths) == 2:
                    break
        else:
            sys.stderr.write("Need 2 paths selected\n")
            return

        pts = [cubicsuperpath.parsePath(paths[i].get("d")) for i in (0, 1)]

        for i in (0, 1):
            if "transform" in paths[i].keys():
                trans = paths[i].get("transform")
                trans = simpletransform.parseTransform(trans)
                simpletransform.applyTransformToPath(trans, pts[i])

        verts = []
        for i in range(0, min(map(len, pts))):
            comp = []
            for j in range(0, min(len(pts[0][i]), len(pts[1][i]))):
                comp.append([pts[0][i][j][1][-2:], pts[1][i][j][1][-2:]])
            verts.append(comp)

        if self.options.mode.lower() == "lines":
            line = []
            for comp in verts:
                for n, v in enumerate(comp):
                    line += [("M", v[0])]
                    line += [("L", v[1])]
            ele = inkex.etree.Element("{http://www.w3.org/2000/svg}path")
            paths[0].xpath("..")[0].append(ele)
            ele.set("d", simplepath.formatPath(line))
            ele.set("style", "fill:none;stroke:#000000;stroke-opacity:1;stroke-width:1;")
        elif self.options.mode.lower() == "polygons":
            g = inkex.etree.Element("{http://www.w3.org/2000/svg}g")
            g.set("style", "fill:#000000;stroke:#000000;fill-opacity:0.3;stroke-width:2;stroke-opacity:0.6;")
            paths[0].xpath("..")[0].append(g)
            for comp in verts:
                for n, v in enumerate(comp):
                    nn = n + 1
                    if nn == len(comp):
                        nn = 0
                    line = []
                    line += [("M", comp[n][0])]
                    line += [("L", comp[n][1])]
                    line += [("L", comp[nn][1])]
                    line += [("L", comp[nn][0])]
                    line += [("L", comp[n][0])]
                    ele = inkex.etree.Element("{http://www.w3.org/2000/svg}path")
                    g.append(ele)
                    ele.set("d", simplepath.formatPath(line))
Пример #6
0
def hpgl(plot):
    #create a preview svg
    svg = etree.Element(inkex.addNS('svg', 'svg'))
    svg.set('height', str(plot.dimensions[1]))
    svg.set(
        'width',
        str(plot.getSize()[0] + plot.startPosition[0] +
            plot.finishPosition[0]))
    svg.set('version', '1.1')
    """
	bg = inkex.etree.Element(inkex.addNS('rect','svg'))
	style = {'fill' : 'none','stroke-opacity': '.8','stroke':'#212425','stroke-width':'10'}
	bg.set('style', simplestyle.formatStyle(style))
	bg.set('x','0')
	bg.set('y','0')
	bg.set('width',str(plot.dimensions[0]))
	bg.set('height',svg.get('height'))
	svg.append(bg)
	"""
    spPU = [['M', [0, 0]]]
    spPD = []
    for c in plot.toHPGL().split(';'):
        if c[:2] == "PU":
            p = map(int, c[2:].split(','))
            spPD.append(['M', p])
            spPU.append(['L', p])
        elif c[:2] == "PD":
            p = map(int, c[2:].split(','))
            spPU.append(['M', p])
            spPD.append(['L', p])

    pu = inkex.etree.Element(inkex.addNS('path', 'svg'))

    simplepath.scalePath(spPU, 0.088582677, -0.088582677)
    simplepath.translatePath(spPU, 0, float(svg.get('height')))

    style = {'fill': 'none', 'stroke-opacity': '.8', 'stroke': '#116AAB'}
    pu.set('style', simplestyle.formatStyle(style))
    pu.set('d', simplepath.formatPath(spPU))

    pd = inkex.etree.Element(inkex.addNS('path', 'svg'))

    style = {'fill': 'none', 'stroke-opacity': '.8', 'stroke': '#AB3011'}
    pd.set('style', simplestyle.formatStyle(style))
    pd.set('d', simplepath.formatPath(spPD))

    # Connect elements together.
    svg.append(pu)
    svg.append(pd)
    return svg
Пример #7
0
def hpgl(plot):
	#create a preview svg
	svg = etree.Element(inkex.addNS('svg','svg'))
	svg.set('height',str(plot.dimensions[1]))
	svg.set('width',str(plot.getSize()[0]+plot.startPosition[0]+plot.finishPosition[0]))
	svg.set('version','1.1')
	"""
	bg = inkex.etree.Element(inkex.addNS('rect','svg'))
	style = {'fill' : 'none','stroke-opacity': '.8','stroke':'#212425','stroke-width':'10'}
	bg.set('style', simplestyle.formatStyle(style))
	bg.set('x','0')
	bg.set('y','0')
	bg.set('width',str(plot.dimensions[0]))
	bg.set('height',svg.get('height'))
	svg.append(bg)
	"""
	spPU = [['M',[0,0]]]
	spPD = []
	for c in plot.toHPGL().split(';'):
		if c[:2] == "PU":
			p = map(int,c[2:].split(','))
			spPD.append(['M',p])
			spPU.append(['L',p])
		elif c[:2] == "PD":
			p = map(int,c[2:].split(','))
			spPU.append(['M',p])
			spPD.append(['L',p])		
	
	pu = inkex.etree.Element(inkex.addNS('path','svg'))
	
	simplepath.scalePath(spPU,0.088582677,-0.088582677)
	simplepath.translatePath(spPU,0,float(svg.get('height')))
	
	style = {'fill' : 'none','stroke-opacity': '.8','stroke':'#116AAB'}
	pu.set('style', simplestyle.formatStyle(style))
	pu.set('d',simplepath.formatPath(spPU))
	
	
	pd = inkex.etree.Element(inkex.addNS('path','svg'))
	
	style = {'fill' : 'none','stroke-opacity': '.8','stroke':'#AB3011'}
	pd.set('style', simplestyle.formatStyle(style))
	pd.set('d',simplepath.formatPath(spPD))
	
	# Connect elements together.
	svg.append(pu)
	svg.append(pd)
	return svg
    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()
    def effect(self):
        gcode = ""
        i = 0
        doc = self.document.getroot()
        factor = self.unittouu(doc.get('width'))
        inkex.debug(factor)

        for id, node in self.selected.iteritems():
            if node.tag == inkex.addNS('path', 'svg'):
                d = node.get('d')
                p = cubicsuperpath.parsePath(d)
                cspsubdiv.cspsubdiv(p, self.options.flat)
                np = []

                first = True
                gcode = "M3 S255(colona " + str(i) + ") \n"  #+"G01 F500.000\n"

                for csp in p[0]:
                    cmd = 'L'
                    if first:
                        cmd = 'M'
                    first = False

                    np.append([cmd, [csp[1][0], csp[1][1]]])
                    gcode += "G01 X" + str(
                        round(self.uutounit(csp[1][0], "mm"), 2)) + " Y" + str(
                            round(self.uutounit(csp[1][1], "mm"), 2)) + "\n"
                    node.set('d', simplepath.formatPath(np))
                f = open("costycnc.nc", 'w')
                f.write(str(gcode))
                f.close()
Пример #10
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)
Пример #11
0
    def snap_path_scale(self, elem, parent_transform=None):
        # If we have a Live Path Effect, modify original-d. If anyone clamours
        # for it, we could make an option to ignore paths with Live Path Effects
        original_d = '{%s}original-d' % inkex.NSS['inkscape']
        path = simplepath.parsePath(elem.attrib.get(original_d, elem.attrib['d']))
        transform = self.transform(elem, parent_transform=parent_transform)
        min_xy, max_xy = self.path_bounding_box(elem, parent_transform)
        
        width = max_xy[0] - min_xy[0]
        height = max_xy[1] - min_xy[1]
        rescale = round(width)/width, round(height)/height

        min_xy = transform_point(transform, min_xy, inverse=True)
        max_xy = transform_point(transform, max_xy, inverse=True)

        for i in range(len(path)):
            self.transform_path_node([[1, 0, -min_xy[0]], [0, 1, -min_xy[1]]], path, i)     # center transform
            self.transform_path_node([[rescale[0], 0, 0],
                                       [0, rescale[1], 0]],
                                       path, i)
            self.transform_path_node([[1, 0, +min_xy[0]], [0, 1, +min_xy[1]]], path, i)     # uncenter transform
        
        path = simplepath.formatPath(path)
        if original_d in elem.attrib: elem.attrib[original_d] = path
        else: elem.attrib['d'] = path
Пример #12
0
    def test_simplepath(self):
        """Test simplepath API"""
        import simplepath

        data = 'M12 34L56 78Z'
        path = simplepath.parsePath(data)
        self.assertEqual(path,
                         [['M', [12., 34.]], ['L', [56., 78.]], ['Z', []]])

        d_out = simplepath.formatPath(path)
        d_out = d_out.replace('.0', '')
        self.assertEqual(data.replace(' ', ''), d_out.replace(' ', ''))

        simplepath.translatePath(path, -3, -4)
        self.assertEqual(path,
                         [['M', [9., 30.]], ['L', [53., 74.]], ['Z', []]])

        simplepath.scalePath(path, 10, 20)
        self.assertEqual(path,
                         [['M', [90., 600.]], ['L', [530., 1480.]], ['Z', []]])

        simplepath.rotatePath(path, math.pi / 2.0, cx=5, cy=7)
        approxed = [[code, approx(coords)] for (code, coords) in path]
        self.assertEqual(
            approxed, [['M', [-588., 92.]], ['L', [-1468., 532.]], ['Z', []]])
    def movePath(self, node, x, y, origin):
        tagName = self.getTagName(node)

        if tagName != "path":
            inkex.debug('movePath only works on SVG Path elements. Argument was of type "' + tagName + '"')
            return False

        path = simplepath.parsePath(node.get("d"))
        id = node.get("id")

        box = list(simpletransform.computeBBox([node]))

        offset_x = box[0] - x
        offset_y = box[2] - (y)

        for cmd in path:
            params = cmd[1]
            i = 0

            while i < len(params):
                if i % 2 == 0:
                    # inkex.debug('x point at ' + str( round( params[i] )))
                    params[i] = params[i] - offset_x
                    # inkex.debug('moved to ' + str( round( params[i] )))
                else:
                    # inkex.debug('y point at ' + str( round( params[i]) ))
                    params[i] = params[i] - offset_y
                    # inkex.debug('moved to ' + str( round( params[i] )))
                i = i + 1

        return simplepath.formatPath(path)
Пример #14
0
    def movePath(self,node,x,y,origin):
        path = node.get('path')
        box = node.get('box')

        #inkex.debug(box)

        offset_x = (box[0] - x)
        offset_y = (box[2] - (y))

        #inkex.debug('Will move path "'+id+'" from x, y ' + str(box[0]) + ', ' + str(box[2]))
        #inkex.debug('to x, y ' + str(x) + ', ' + str(y))

        #inkex.debug('The x offset is ' + str(offset_x))
        #inkex.debug('The y offset is = ' + str(offset_y))


        for cmd in path:
            params = cmd[1]
            i = 0

            while(i < len(params)):
                if(i % 2 == 0):
                    #inkex.debug('x point at ' + str( round( params[i] )))
                    params[i] = (params[i] - offset_x)
                    #inkex.debug('moved to ' + str( round( params[i] )))
                else:
                    #inkex.debug('y point at ' + str( round( params[i]) ))
                    params[i] = (params[i] - offset_y)
                    #inkex.debug('moved to ' + str( round( params[i] )))
                i = i + 1


        #inkex.debug(simplepath.formatPath(path))
        return simplepath.formatPath(path)
Пример #15
0
 def effect(self):
     for id, node in self.selected.iteritems():
         if node.tag == inkex.addNS('path', 'svg'):
             d = node.get('d')
             p = simplepath.parsePath(d)
             last = []
             subPathStart = []
             for cmd, params in p:
                 if cmd == 'C':
                     if self.options.behave <= 1:
                         #shorten handles towards end points
                         params[:2] = pointAtPercent(
                             params[:2], last[:], self.options.percent)
                         params[2:4] = pointAtPercent(
                             params[2:4], params[-2:], self.options.percent)
                     else:
                         #shorten handles towards thirds of the segment
                         dest1 = pointAtPercent(last[:], params[-2:], 33.3)
                         dest2 = pointAtPercent(params[-2:], last[:], 33.3)
                         params[:2] = pointAtPercent(
                             params[:2], dest1[:], self.options.percent)
                         params[2:4] = pointAtPercent(
                             params[2:4], dest2[:], self.options.percent)
                 elif cmd == 'Q':
                     dest = pointAtPercent(last[:], params[-2:], 50)
                     params[:2] = pointAtPercent(params[:2], dest,
                                                 self.options.percent)
                 if cmd == 'M':
                     subPathStart = params[-2:]
                 if cmd == 'Z':
                     last = subPathStart[:]
                 else:
                     last = params[-2:]
             node.set('d', simplepath.formatPath(p))
Пример #16
0
 def effect(self):
     for id, node in self.selected.iteritems():
         if node.tag == inkex.addNS('path', 'svg'):
             d = node.get('d')
             p = simplepath.parsePath(d)
             last = []
             subPathStart = []
             for cmd,params in p:
                 if cmd == 'C':
                     if self.options.behave <= 1:
                         #shorten handles towards end points
                         params[:2] = pointAtPercent(params[:2],last[:],self.options.percent)    
                         params[2:4] = pointAtPercent(params[2:4],params[-2:],self.options.percent)
                     else:
                         #shorten handles towards thirds of the segment                            
                         dest1 = pointAtPercent(last[:],params[-2:],33.3)
                         dest2 = pointAtPercent(params[-2:],last[:],33.3)
                         params[:2] = pointAtPercent(params[:2],dest1[:],self.options.percent)    
                         params[2:4] = pointAtPercent(params[2:4],dest2[:],self.options.percent)
                 elif cmd == 'Q':
                     dest = pointAtPercent(last[:],params[-2:],50)
                     params[:2] = pointAtPercent(params[:2],dest,self.options.percent)
                 if cmd == 'M':
                     subPathStart = params[-2:]
                 if cmd == 'Z':
                     last = subPathStart[:]
                 else:
                     last = params[-2:]
             node.set('d',simplepath.formatPath(p))
  def effect(self):
    clippingLineSegments = None
    pathTag = inkex.addNS('path','svg')
    groupTag = inkex.addNS('g','svg')
    error_messages = []
    for id in self.options.ids:  # the selection, top-down
      node = self.selected[id]
      if node.tag == pathTag:
        if clippingLineSegments is None: # first path is the clipper
          (clippingLineSegments, errors) = self.simplepathToLineSegments(simplepath.parsePath(node.get('d')))
          error_messages.extend(['{}: {}'.format(id, err) for err in errors])
        else:
          # do all the work!
          segmentsToClip, errors = self.simplepathToLineSegments(simplepath.parsePath(node.get('d')))
          error_messages.extend(['{}: {}'.format(id, err) for err in errors])
          clippedSegments = self.clipLineSegments(segmentsToClip, clippingLineSegments)
          if len(clippedSegments) != 0:
            # replace the path
            node.set('d', simplepath.formatPath(self.linesgmentsToSimplePath(clippedSegments)))
          else:
            # don't put back an empty path(?)  could perhaps put move, move?
            inkex.debug('Object {} clipped to nothing, will not be updated.'.format(node.get('id')))
      elif node.tag == groupTag:  # we don't look inside groups for paths
        inkex.debug('Group object {} will be ignored. Please ungroup before running the script.'.format(id))
      else: # something else
        inkex.debug('Object {} is not of type path ({}), and will be ignored. Current type "{}".'.format(id, pathTag, node.tag))

    for error in error_messages:
        inkex.debug(error)
Пример #18
0
    def snap_path_pos(self, elem, parent_transform=None):
        """ Goes through each node in the given path and modifies it as
            necessary in order to shift the entire path by the required
            (calculated) distance.
        """

        # If we have a Live Path Effect, modify original-d. If anyone clamours
        # for it, we could make an option to ignore paths with Live Path Effects
        original_d = '{%s}original-d' % inkex.NSS['inkscape']
        path = simplepath.parsePath(
            elem.attrib.get(original_d, elem.attrib['d']))
        transform = self.get_transform(elem, parent_transform)
        min_xy, max_xy = self.path_bounding_box(elem, parent_transform)

        fractional_offset = min_xy[0] - round(min_xy[0]), min_xy[1] - round(
            min_xy[1]) - self.document_offset
        fractional_offset = transform_dimensions(transform,
                                                 fractional_offset[0],
                                                 fractional_offset[1],
                                                 inverse=True)

        for i in range(len(path)):
            self.transform_path_node(
                [[1, 0, -fractional_offset[0]], [0, 1, -fractional_offset[1]]],
                path, i)

        path = simplepath.formatPath(path)
        if original_d in elem.attrib: elem.attrib[original_d] = path
        else: elem.attrib['d'] = path
Пример #19
0
    def snap_path_scale(self, elem, parent_transform=None):
        # If we have a Live Path Effect, modify original-d. If anyone clamours
        # for it, we could make an option to ignore paths with Live Path Effects
        original_d = "{%s}original-d" % inkex.NSS["inkscape"]
        path = simplepath.parsePath(elem.attrib.get(original_d, elem.attrib["d"]))
        transform = self.transform(elem, parent_transform=parent_transform)
        min_xy, max_xy = self.path_bounding_box(elem, parent_transform)

        width = max_xy[0] - min_xy[0]
        height = max_xy[1] - min_xy[1]

        # In case somebody tries to snap a 0-high element,
        # or a curve/arc with all nodes in a line, and of course
        # because we should always check for divide-by-zero!
        if width == 0 or height == 0:
            return

        rescale = round(width) / width, round(height) / height

        min_xy = transform_point(transform, min_xy, inverse=True)
        max_xy = transform_point(transform, max_xy, inverse=True)

        for i in range(len(path)):
            self.transform_path_node([[1, 0, -min_xy[0]], [0, 1, -min_xy[1]]], path, i)  # center transform
            self.transform_path_node([[rescale[0], 0, 0], [0, rescale[1], 0]], path, i)
            self.transform_path_node([[1, 0, +min_xy[0]], [0, 1, +min_xy[1]]], path, i)  # uncenter transform

        path = simplepath.formatPath(path)
        if original_d in elem.attrib:
            elem.attrib[original_d] = path
        else:
            elem.attrib["d"] = path
Пример #20
0
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tag == inkex.addNS('path','svg'):
                p = simplepath.parsePath(node.get('d'))
                a =[]
                pen = None
                subPathStart = None
                for cmd,params in p:
                    if cmd == 'C':
                        a.extend([['M', params[:2]], ['L', pen],
                            ['M', params[2:4]], ['L', params[-2:]]])
                    if cmd == 'Q':
                        a.extend([['M', params[:2]], ['L', pen],
                            ['M', params[:2]], ['L', params[-2:]]])
                    
                    if cmd == 'M':
                        subPathStart = params

                    if cmd == 'Z':
                        pen = subPathStart
                    else:
                        pen = params[-2:]
                    
                if len(a) > 0:
                    s = {'stroke-linejoin': 'miter', 'stroke-width': '1.0px', 
                        'stroke-opacity': '1.0', 'fill-opacity': '1.0', 
                        'stroke': '#000000', 'stroke-linecap': 'butt', 
                        'fill': 'none'}
                    attribs = {'style':simplestyle.formatStyle(s),'d':simplepath.formatPath(a)}
                    inkex.etree.SubElement(node.getparent(), inkex.addNS('path','svg'), attribs)
Пример #21
0
    def snap_path_scale(self, elem, parent_transform=None):
        # If we have a Live Path Effect, modify original-d. If anyone clamours
        # for it, we could make an option to ignore paths with Live Path Effects
        original_d = '{%s}original-d' % inkex.NSS['inkscape']
        path = simplepath.parsePath(
            elem.attrib.get(original_d, elem.attrib['d']))
        transform = self.transform(elem, parent_transform=parent_transform)
        min_xy, max_xy = self.path_bounding_box(elem, parent_transform)

        width = max_xy[0] - min_xy[0]
        height = max_xy[1] - min_xy[1]

        # In case somebody tries to snap a 0-high element,
        # or a curve/arc with all nodes in a line, and of course
        # because we should always check for divide-by-zero!
        if (width == 0 or height == 0): return

        rescale = round(width) / width, round(height) / height

        min_xy = transform_point(transform, min_xy, inverse=True)
        max_xy = transform_point(transform, max_xy, inverse=True)

        for i in range(len(path)):
            self.transform_path_node([[1, 0, -min_xy[0]], [0, 1, -min_xy[1]]],
                                     path, i)  # center transform
            self.transform_path_node([[rescale[0], 0, 0], [0, rescale[1], 0]],
                                     path, i)
            self.transform_path_node([[1, 0, +min_xy[0]], [0, 1, +min_xy[1]]],
                                     path, i)  # uncenter transform

        path = simplepath.formatPath(path)
        if original_d in elem.attrib: elem.attrib[original_d] = path
        else: elem.attrib['d'] = path
Пример #22
0
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tagName == 'path':
                p = simplepath.parsePath(node.attributes.getNamedItem('d').value)
                a =[]
                pen = None
                subPathStart = None
                for cmd,params in p:
                    if cmd == 'C':
                        a.extend([['M', params[:2]], ['L', pen],
                            ['M', params[2:4]], ['L', params[-2:]]])
                    if cmd == 'Q':
                        a.extend([['M', params[:2]], ['L', pen],
                            ['M', params[:2]], ['L', params[-2:]]])
                    
                    if cmd == 'M':
                        subPathStart = params

                    if cmd == 'Z':
                        pen = subPathStart
                    else:
                        pen = params[-2:]
                    
                if len(a) > 0:
                    new = self.document.createElement('svg:path')
                    s = {'stroke-linejoin': 'miter', 'stroke-width': '1.0px', 
                        'stroke-opacity': '1.0', 'fill-opacity': '1.0', 
                        'stroke': '#000000', 'stroke-linecap': 'butt', 
                        'fill': 'none'}
                    new.setAttribute('style', simplestyle.formatStyle(s))
                    new.setAttribute('d', simplepath.formatPath(a))
                    node.parentNode.appendChild(new)
Пример #23
0
    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()
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tag == inkex.addNS('path', 'svg'):
                d = node.get('d')
                p = simplepath.parsePath(d)

                a = []
                first = 1
                for cmd, params in p:
                    if cmd != 'Z':
                        if first == 1:
                            x1 = params[-2]
                            y1 = params[-1]
                            a.append(['M', params[-2:]])
                            first = 2
                        else:
                            x2 = params[-2]
                            y2 = params[-1]
                            self.fractalize(a, x1, y1, x2, y2,
                                            self.options.subdivs,
                                            self.options.smooth)
                            x1 = x2
                            y1 = y2
                            a.append(['L', params[-2:]])

                node.set('d', simplepath.formatPath(a))
    def effect(self):
        zoom = self.unittouu(str(self.options.zoom) + 'px')

        if self.options.randomize:
            imagelist = generate_random_string(self.options.text, zoom)
        else:
            tokens = tokenize(self.options.text)
            imagelist = randomize_input_string(tokens, zoom)

        image = layoutstring(imagelist, zoom)

        if image:
            s = {'stroke': 'none', 'fill': '#000000'}

            new = inkex.etree.Element(inkex.addNS('path', 'svg'))
            new.set('style', simplestyle.formatStyle(s))

            new.set('d', simplepath.formatPath(image))
            self.current_layer.append(new)

            # compensate preserved transforms of parent layer
            if self.current_layer.getparent() is not None:
                mat = simpletransform.composeParents(
                    self.current_layer, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
                simpletransform.applyTransformToNode(
                    simpletransform.invertTransform(mat), new)
Пример #26
0
def realistic_stitch(start, end):
    """Generate a stitch vector path given a start and end point."""

    end = Point(*end)
    start = Point(*start)

    stitch_length = (end - start).length()
    stitch_center = (end + start) / 2.0
    stitch_direction = (end - start)
    stitch_angle = math.atan2(stitch_direction.y, stitch_direction.x)

    stitch_length = max(0, stitch_length - 0.2 * PIXELS_PER_MM)

    # create the path by filling in the length in the template
    path = simplepath.parsePath(stitch_path % stitch_length)

    # rotate the path to match the stitch
    rotation_center_x = -stitch_length / 2.0
    rotation_center_y = stitch_height / 2.0
    simplepath.rotatePath(path,
                          stitch_angle,
                          cx=rotation_center_x,
                          cy=rotation_center_y)

    # move the path to the location of the stitch
    simplepath.translatePath(path, stitch_center.x - rotation_center_x,
                             stitch_center.y - rotation_center_y)

    return simplepath.formatPath(path)
Пример #27
0
    def effect(self):
        """This is the main entry point"""

        # based partially on the restack.py extension
        if len(self.selected) > 0:
            # TODO check for non-path elements?
            # TODO it seems like the order of selection is not consistent
            # => self.selected is a dict so it has no meaningful order and should not be used to evaluate the original path length

            #fid = open("/home/matthew/debug.txt", "w")

            # for each selected item
            # I can think of two options:
            # 1. Iterate over all paths in root, then iterate over all layers, and their paths
            # 2. Some magic with xpath? (would this limit us to specific node types?)

            objlist = []
            for id, node in self.selected.iteritems():
                (sx, sy, ex, ey) = self.get_start_end(node)
                path = Path(id, (sx, sy), (ex, ey))
                objlist.append(path)

            # sort / order the objects
            sort_order, air_distance_default, air_distance_ordered = find_ordering(
                objlist, self.options.allowReverse)

            reverseCount = 0
            for path in sort_order:
                node = self.selected[path.id]
                if node.tag == inkex.addNS('path', 'svg'):
                    node_sp = simplepath.parsePath(node.get('d'))
                    if (path.reversed):
                        node_sp_string = reversePath(node_sp)
                        reverseCount += 1
                    else:
                        node_sp_string = simplepath.formatPath(node_sp)

                    node.set('d', node_sp_string)

                #keep in mind the different selected ids might have different parents
                self.getParentNode(node).append(node)

            inkex.errormsg("Reversed {} paths.".format(reverseCount))
            #fid.close()

            if air_distance_default > 0:  # don't divide by zero. :P
                improvement_pct = 100 * (
                    (air_distance_default - air_distance_ordered) /
                    (air_distance_default))
                inkex.errormsg(
                    gettext.gettext(
                        "Selected paths have been reordered and optimized for quicker EggBot plotting.\n\nDefault air-distance: %d\nOptimized air-distance: %d\nDistance reduced by: %1.2d%%\n\nHave a nice day!"
                        % (air_distance_default, air_distance_ordered,
                           improvement_pct)))
            else:
                inkex.errormsg(
                    gettext.gettext(
                        "Unable to start. Please select multiple distinct paths. :)"
                    ))
Пример #28
0
 def d_path(self):
     a = list()
     a.append( ['M ', [self.x, self.y]] )
     a.append( [' l ', [self.width, 0]] )
     a.append( [' l ', [0, self.height]] )
     a.append( [' l ', [-self.width, 0]] )
     a.append( [' Z', []] )
     return simplepath.formatPath(a)     
Пример #29
0
 def d_path(self):
     a = list()
     a.append( ['M ', [self.x, self.y]] )
     a.append( [' l ', [self.width, 0]] )
     a.append( [' l ', [0, self.height]] )
     a.append( [' l ', [-self.width, 0]] )
     a.append( [' Z', []] )
     return simplepath.formatPath(a)     
Пример #30
0
    def draw_slots(self, path):
        #Female slot creation

        start = self.to_complex(path[0][1])
        end = self.to_complex(path[1][1])

        if self.edgefeatures == False:
            segCount = (self.numslots * 2)
        else:
            segCount = (self.numslots * 2) - 1

        distance = end - start
        debugMsg(distance)
        debugMsg("segCount - " + str(segCount))

        try:
            if self.edgefeatures:
                segLength = self.get_length(distance) / segCount
            else:
                segLength = self.get_length(distance) / (segCount + 1)
        except:
            segLength = self.get_length(distance)

        debugMsg("segLength - " + str(segLength))
        newLines = []

        line_style = simplestyle.formatStyle({
            'stroke':
            '#000000',
            'fill':
            'none',
            'stroke-width':
            str(self.unittouu('1px'))
        })

        for i in range(segCount):
            if (self.edgefeatures and
                (i % 2) == 0) or (not self.edgefeatures and (i % 2)):
                newLines = self.draw_box(start, distance, segLength,
                                         self.thickness, self.kerf)
                debugMsg(newLines)

                slot_id = self.uniqueId('slot')
                g = inkex.etree.SubElement(self.current_layer, 'g',
                                           {'id': slot_id})

                line_atts = {
                    'style': line_style,
                    'id': slot_id + '-inner-close-tab',
                    'd': simplepath.formatPath(newLines)
                }
                inkex.etree.SubElement(g, inkex.addNS('path', 'svg'),
                                       line_atts)

            #Find next point
            polR, polPhi = cmath.polar(distance)
            polR = segLength
            start = cmath.rect(polR, polPhi) + start
def addPath(newList, refnode):
    """Add a node in the xml structure corresponding to the content of newList
    newList : list of Segment or Path
    refnode : xml node used as a reference, new point will be inserted a same level"""
    ele = etree.Element('{http://www.w3.org/2000/svg}path')
    errwrite("newList = " + str(newList) + "\n")
    ele.set('d', simplepath.formatPath(newList))
    refnode.xpath('..')[0].append(ele)
    return ele
def getTranslatedPath(d, posX, posY):
    if(CommonDefs.inkVer == 1.0):
        path = Path(d)
        path.translate(posX, posY, inplace = True)
        return path.to_superpath().__str__()
    else:
        path = simplepath.parsePath(d)
        simplepath.translatePath(path, posX, posY)
        return simplepath.formatPath(path)
Пример #33
0
    def process_path(self, ipath, mat_x, mat_y, term1):
        mat = simpletransform.composeParents(
            ipath, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
        path_string = ipath.get('d')
        svg_path = simplepath.parsePath(path_string)

        paths = []

        # for path in svg_path:
        # inkex.debug("svg_path: " + str(svg_path))
        for path in svg_path:
            if path[0] == 'M' or path[0] == 'L':
                paths.append([path[0], [path[1]]])
            elif path[0] == 'C' or path[0] == 'Q':
                pts = []
                if path[0] == 'C':
                    num = 3
                else:
                    num = 2
                for i in range(0, num):
                    pt = [path[1][2 * i], path[1][2 * i + 1]]
                    pts.append(pt)
                paths.append([path[0], pts])

            elif path[0] == 'Z':
                paths.append(['Z', []])

        # inkex.debug("paths: " + str(paths) + "\n\n")
        mat = simpletransform.invertTransform(mat)
        # simpletransform.applyTransformToPath(mat, p)
        for path in paths:
            for pt in path[1]:
                simpletransform.applyTransformToPoint(mat, pt)

        # do transformation
        for path in paths:
            for pt in path[1]:
                self.project_point(pt, mat_x, mat_y, term1)

        # back to original form
        res_paths = []
        for path in paths:
            if path[0] == 'C' or path[0] == 'Q':
                flat_pts = []
                for pt in path[1]:
                    flat_pts.append(pt[0])
                    flat_pts.append(pt[1])
                res_paths.append([path[0], flat_pts])
            elif path[0] == 'M' or path[0] == 'L':
                res_paths.append([path[0], path[1][0]])
            elif path[0] == 'Z':
                res_paths.append(path)
        # inkex.debug("res_paths: " + str(res_paths))
        res_svg_paths = simplepath.formatPath(res_paths)
        # inkex.debug("res_svg_paths: " + str(res_svg_paths))
        ipath.set('d', res_svg_paths)
	def effect( self ):

		inkex.NSS[self.nsPrefix] = self.nsURI

		if self.options.bLace:
			func = 'lace'
		else:
			func = 'sine'

		fRecess = float( 1 )
		if self.options.fRecess > 0.0:
			fRecess = 1.0 - self.options.fRecess / float( 100 )
			if fRecess <= 0.0:
				fRecess = float( 0 )

		if self.options.ids:
			if len( self.options.ids ) == 2:
				attr = self.selected[self.options.ids[0]].attrib
				desc1 = self.selected[self.options.ids[0]].get( inkex.addNS( 'desc', self.nsPrefix ) )
				desc2 = self.selected[self.options.ids[1]].get( inkex.addNS( 'desc', self.nsPrefix ) )
				if ( not desc1 ) or ( not desc2 ):
					inkex.errormsg( 'Selected objects do not smell right' )
					return
				path_data, path_desc = drawSine( self.options.fCycles,
					self.options.nrN,
					self.options.nrM,
					self.options.nSamples,
					[ self.options.nOffsetX, self.options.nOffsetY ],
					self.options.nHeight,
					self.options.nWidth,
					fRecess,
					desc1, desc2, func, self.options.bSpline )
			else:
				inkex.errormsg( 'Exactly two objects must be selected' )
				return
		else:
			self.document.getroot().set( inkex.addNS( self.nsPrefix, 'xmlns' ), self.nsURI )

			path_data, path_desc = drawSine( self.options.fCycles,
				self.options.nrN,
				self.options.nrM,
				self.options.nSamples,
				[ self.options.nOffsetX, self.options.nOffsetY ],
				self.options.nHeight,
				self.options.nWidth,
				fRecess,
				None, None, func, self.options.bSpline )

		style = { 'stroke': 'black', 'stroke-width': '1', 'fill': 'none' }
		path_attrs = {
			'style': simplestyle.formatStyle( style ),
			'd': simplepath.formatPath( path_data ),
			inkex.addNS( 'desc', self.nsPrefix ): path_desc }
		newpath = inkex.etree.SubElement( self.document.getroot(),
			inkex.addNS( 'path', 'svg '), path_attrs, nsmap=inkex.NSS )
Пример #35
0
    def effect(self):

        inkex.NSS[self.nsPrefix] = self.nsURI

        if self.options.bLace:
            func = 'lace'
        else:
            func = 'sine'

        fRecess = float(1)
        if self.options.fRecess > 0.0:
            fRecess = 1.0 - self.options.fRecess / float(100)
            if fRecess <= 0.0:
                fRecess = float(0)

        if self.options.ids:
            if len(self.options.ids) == 2:
                attr = self.selected[self.options.ids[0]].attrib
                desc1 = self.selected[self.options.ids[0]].get(
                    inkex.addNS('desc', self.nsPrefix))
                desc2 = self.selected[self.options.ids[1]].get(
                    inkex.addNS('desc', self.nsPrefix))
                if (not desc1) or (not desc2):
                    inkex.errormsg('Selected objects do not smell right')
                    return
                path_data, path_desc = drawSine(
                    self.options.fCycles, self.options.nrN, self.options.nrM,
                    self.options.nSamples,
                    [self.options.nOffsetX, self.options.nOffsetY],
                    self.options.nHeight, self.options.nWidth, fRecess, desc1,
                    desc2, func, self.options.bSpline)
            else:
                inkex.errormsg('Exactly two objects must be selected')
                return
        else:
            self.document.getroot().set(inkex.addNS(self.nsPrefix, 'xmlns'),
                                        self.nsURI)

            path_data, path_desc = drawSine(
                self.options.fCycles, self.options.nrN, self.options.nrM,
                self.options.nSamples,
                [self.options.nOffsetX, self.options.nOffsetY],
                self.options.nHeight, self.options.nWidth, fRecess, None, None,
                func, self.options.bSpline)

        style = {'stroke': 'black', 'stroke-width': '1', 'fill': 'none'}
        path_attrs = {
            'style': simplestyle.formatStyle(style),
            'd': simplepath.formatPath(path_data),
            inkex.addNS('desc', self.nsPrefix): path_desc
        }
        newpath = inkex.etree.SubElement(self.document.getroot(),
                                         inkex.addNS('path', 'svg '),
                                         path_attrs,
                                         nsmap=inkex.NSS)
Пример #36
0
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tag == inkex.addNS("rect", "svg"):
                # create new path with basic dimensions of selected rectangle
                newpath = inkex.etree.Element(inkex.addNS("path", "svg"))
                x = float(node.get("x"))
                y = float(node.get("y"))
                w = float(node.get("width"))
                h = float(node.get("height"))

                # copy attributes of rect
                s = node.get("style")
                if s:
                    newpath.set("style", s)

                t = node.get("transform")
                if t:
                    newpath.set("transform", t)

                # top and bottom were exchanged
                newpath.set(
                    "d",
                    simplepath.formatPath(
                        drawfunction(
                            self.options.t_start,
                            self.options.t_end,
                            self.options.xleft,
                            self.options.xright,
                            self.options.ybottom,
                            self.options.ytop,
                            self.options.samples,
                            w,
                            h,
                            x,
                            y + h,
                            self.options.fofx,
                            self.options.fofy,
                            self.options.times2pi,
                            self.options.isoscale,
                            self.options.drawaxis,
                        )
                    ),
                )
                newpath.set("title", self.options.fofx + " " + self.options.fofy)

                # newpath.set('desc', '!func;' + self.options.fofx + ';' + self.options.fofy + ';'
                #                                      + `self.options.t_start` + ';'
                #                                      + `self.options.t_end` + ';'
                #                                      + `self.options.samples`)

                # add path into SVG structure
                node.getparent().append(newpath)
                # option wether to remove the rectangle or not.
                if self.options.remove:
                    node.getparent().remove(node)
Пример #37
0
 def load(self, node, mat):
   newpath = new_path_from_node(node)
   x1 = float(node.get('x1'))
   y1 = float(node.get('y1'))
   x2 = float(node.get('x2'))
   y2 = float(node.get('y2'))
   a = []
   a.append(['M ', [x1,y1]])
   a.append([' L ', [x2,y2]])
   newpath.set('d', simplepath.formatPath(a))
   SvgPath.load(self,newpath,mat)
Пример #38
0
 def load(self, node, mat):
   newpath = self.new_path_from_node(node)
   x1 = float(node.get('x1'))
   y1 = float(node.get('y1'))
   x2 = float(node.get('x2'))
   y2 = float(node.get('y2'))
   a = []
   a.append(['M ', [x1,y1]])
   a.append([' L ', [x2,y2]])
   newpath.set('d', simplepath.formatPath(a))
   SvgPath.load(self,newpath,mat)
def connect (parent, start_node, end_node, style_dict, overwrite=False) :
	if overwrite or not already_connected(parent,start_node,end_node) :
		con = inkex.etree.SubElement(parent,inkex.addNS('path','svg'))
		#con.set("id",self.uniqueId("con"))
		con.set(inkex.addNS('connection-start','inkscape'),"#%s" % start_node.get("id"))
		con.set(inkex.addNS('connection-end','inkscape'),"#%s" % end_node.get("id"))
		con.set(inkex.addNS('connector-type','inkscape'),"polyline")
		path=[['M',element_center(start_node)],['L',element_center(end_node)]]
		con.set("d",simplepath.formatPath(path))
		style={"stroke":simplestyle.svgcolors["magenta"]}
		con.set("style",simplestyle.formatStyle(style_dict))
		return con
Пример #40
0
    def effect(self):
        newpath = None
        for id, node in self.selected.iteritems():
            if node.tag == inkex.addNS('rect','svg'):
                # create new path with basic dimensions of selected rectangle
                newpath = inkex.etree.Element(inkex.addNS('path','svg'))
                x = float(node.get('x'))
                y = float(node.get('y'))
                w = float(node.get('width'))
                h = float(node.get('height'))

                #copy attributes of rect
                s = node.get('style')
                if s:
                    newpath.set('style', s)
                
                t = node.get('transform')
                if t:
                    newpath.set('transform', t)
                    
                # top and bottom were exchanged
                newpath.set('d', simplepath.formatPath(
                            drawfunction(self.options.xstart,
                                self.options.xend,
                                self.options.ybottom,
                                self.options.ytop,
                                self.options.samples, 
                                w,h,x,y+h,
                                self.options.fofx, 
                                self.options.fpofx,
                                self.options.fponum,
                                self.options.times2pi,
                                self.options.polar,
                                self.options.isoscale,
                                self.options.drawaxis,
                                self.options.endpts)))
                newpath.set('title', self.options.fofx)
                
                #newpath.setAttribute('desc', '!func;' + self.options.fofx + ';' 
                #                                      + self.options.fpofx + ';'
                #                                      + `self.options.fponum` + ';'
                #                                      + `self.options.xstart` + ';'
                #                                      + `self.options.xend` + ';'
                #                                      + `self.options.samples`)
                                
                # add path into SVG structure
                node.getparent().append(newpath)
                # option wether to remove the rectangle or not.
                if self.options.remove:
                    node.getparent().remove(node)
        if newpath is None:
            inkex.errormsg(_("Please select a rectangle"))
Пример #41
0
    def place(self, nodes):
        max_line_width = self.unittouu('450mm')

        x_gap = y_gap = self.unittouu('10mm')
        x_start = self.unittouu('3mm')
        y_start = self.unittouu('1600mm') - self.unittouu('3mm')

        total_width = 0
        total_height = 0

        line_nodes = []

        group = etree.SubElement(self.current_layer, addNS('g', 'svg'))

        for id, node, bbox in nodes:
            x, _, y, _ = bbox

            node_width = x_gap + self.width(bbox)
            # reached end of line, reset, move higher, start new group
            if total_width + node_width > max_line_width:
                group = etree.SubElement(self.current_layer, addNS('g', 'svg'))
                total_width = 0
                total_height += self.height(
                    self.computeBBox(line_nodes)) + y_gap
                line_nodes = []

            group.append(node)

            x_dest = x_start + total_width
            y_dest = y_start - (total_height + self.height(bbox))

            if node.tag == addNS('path', 'svg'):
                x_delta = x_dest - x
                y_delta = y_dest - y

                path = parsePath(node.attrib['d'])
                translatePath(path, x_delta, y_delta)
                node.attrib['d'] = formatPath(path)
            elif node.tag == addNS('g', 'svg'):
                x_delta = x_dest - x
                y_delta = y_dest - y

                translation_matrix = [[1.0, 0.0, x_delta], [0.0, 1.0, y_delta]]
                applyTransformToNode(translation_matrix, node)

            else:
                node.attrib['x'] = str(x_dest)
                node.attrib['y'] = str(y_dest)

            total_width += node_width
            line_nodes.append(node)
Пример #42
0
    def effect(self):

        pathTag = inkex.addNS('path', 'svg')

        for id, node in self.selected.iteritems():
            if node.tag == pathTag:
                d = node.get('d')
                path = simplepath.parsePath(d)
                newPath = []
                start = prev = None
                seenSegments = set()
                pathclosed = True
                for command, coords in path:
                    tcoords = tuple(coords)
                    if command == 'M':
                        newPath.append([command, coords])
                        start = prev = tcoords
                        pathclosed = True
                    elif command == 'L':
                        if ('L', prev, tcoords) in seenSegments or \
                           ('L', tcoords, prev) in seenSegments:
                            newPath.append(['M', coords])
                            pathclosed = False
                        else:
                            newPath.append([command, coords])
                            seenSegments.add(('L', prev, tcoords))
                        prev = tcoords
                    elif command == 'Z':
                        if ('L', prev, start) in seenSegments or \
                           ('L', start, prev) in seenSegments:
                            newPath.append(['M', start])
                        else:
                            if pathclosed:
                                newPath.append([command, coords])
                            else:
                                newPath.append(['L', start])
                            seenSegments.add(('L', prev, start))
                        prev = start
                    elif command == 'C':
                        if ('C', prev, tcoords) in seenSegments or \
                           ('C', tcoords[4:], (tcoords[2:4], tcoords[0:2], prev)) in seenSegments:
                            newPath.append(['M', coords[4:]])
                        else:
                            newPath.append(['C', coords])
                            seenSegments.add(('C', prev, tcoords))
                        prev = tcoords[4:]
                    else:
                        newPath.append([command, coords])
                while len(newPath) and newPath[-1][0] == 'M':
                    newPath = newPath[:-1]
                node.set('d', simplepath.formatPath(newPath))
Пример #43
0
 def curveto(p0, curve, flat):
     poly = []
     d = simplepath.formatPath([['M', p0], curve])
     p = cubicsuperpath.parsePath(d)
     cspsubdiv.cspsubdiv(p, flat)
     for sp in p:
         first = True
         for csp in sp:
             if first:
                 first = False
             else:
                 for subpath in csp:
                     poly.append(['L', list(subpath)])
     return poly
Пример #44
0
		def curveto(p0,curve,flat):
			poly = []
			d = simplepath.formatPath([['M',p0],curve])
			p = cubicsuperpath.parsePath(d)
			cspsubdiv.cspsubdiv(p, flat)
			for sp in p:
				first = True
				for csp in sp:
					if first:
						first = False
					else:
						for subpath in csp:	
							poly.append(['L',list(subpath)])
			return poly
Пример #45
0
 def load(self, node, mat):
   newpath = self.new_path_from_node(node)
   x = float(node.get('x'))
   y = float(node.get('y'))
   w = float(node.get('width'))
   h = float(node.get('height'))
   a = []
   a.append(['M ', [x,y]])
   a.append([' l ', [w,0]])
   a.append([' l ', [0,h]])
   a.append([' l ', [-w,0]])
   a.append([' Z', []])
   newpath.set('d', simplepath.formatPath(a))
   SvgPath.load(self,newpath,mat)
Пример #46
0
    def place(self, nodes):
        max_line_width = self.unittouu('450mm')

        x_gap = y_gap = self.unittouu('10mm')
        x_start = self.unittouu('3mm')
        y_start = self.unittouu('1600mm') - self.unittouu('3mm')

        total_width = 0
        total_height = 0

        line_nodes = []

        group = etree.SubElement(self.current_layer, addNS('g','svg'))

        for id, node, bbox in nodes:
            x, _, y, _ = bbox

            node_width = x_gap + self.width(bbox)
            # reached end of line, reset, move higher, start new group
            if total_width + node_width > max_line_width:
                group = etree.SubElement(self.current_layer, addNS('g','svg'))
                total_width = 0
                total_height += self.height(self.computeBBox(line_nodes)) + y_gap
                line_nodes = []

            group.append(node)

            x_dest = x_start + total_width
            y_dest = y_start - (total_height + self.height(bbox))

            if node.tag == addNS('path','svg'):
                x_delta = x_dest - x
                y_delta = y_dest - y

                path = parsePath(node.attrib['d'])
                translatePath(path, x_delta, y_delta)
                node.attrib['d'] = formatPath(path)
            elif node.tag == addNS('g','svg'):
                x_delta = x_dest - x
                y_delta = y_dest - y

                translation_matrix = [[1.0, 0.0, x_delta], [0.0, 1.0, y_delta]]
                applyTransformToNode(translation_matrix, node)

            else:
                node.attrib['x'] = str(x_dest)
                node.attrib['y'] = str(y_dest)

            total_width += node_width
            line_nodes.append(node)
Пример #47
0
 def load(self, node, mat):
   newpath = self.new_path_from_node(node)
   x = float(node.get('x'))
   y = float(node.get('y'))
   w = float(node.get('width'))
   h = float(node.get('height'))
   a = []
   a.append(['M ', [x,y]])
   a.append([' l ', [w,0]])
   a.append([' l ', [0,h]])
   a.append([' l ', [-w,0]])
   a.append([' Z', []])
   newpath.set('d', simplepath.formatPath(a))
   SvgPath.load(self,newpath,mat)
Пример #48
0
def fuse_subpaths(path_node):
    """Fuse subpaths of a path. Should only be used on unstroked paths"""
    path_d = path_node.get("d", None)
    path = simplepath.parsePath(path_d)

    if len(path) == 0:
        return

    i = 0
    initial_point = [ path[i][1][-2], path[i][1][-1] ]
    return_stack = []
    while i < len(path):
        # Remove any terminators: they are redundant
        if path[i][0] == "Z":
            path.remove(["Z", []])
            continue

        # Skip all elements that do not begin a new path
        if i == 0 or path[i][0] != "M":
            i += 1
            continue

        # This element begins a new path - it should be a moveto
        assert(path[i][0] == 'M')

        # Swap it for a lineto
        path[i][0] = 'L'

        # If the old subpath has not been closed yet, close it
        if path[i-1][1][-2] != initial_point[0] or path[i-1][1][-2] != initial_point[1]:
            path.insert(i, ['L', initial_point])
            i += 1

        # Set the initial point of this subpath
        initial_point = [ path[i-1][1][-2], path[i-1][1][-1] ]

        # Append this point to the return stack
        return_stack.append(initial_point)
    #end while

    # Now pop the entire return stack
    while return_stack != []:
        el = ['L', return_stack.pop()]
        path.insert(i, el)
        i += 1


    path_d = simplepath.formatPath(path)
    path_node.set("d", path_d)
Пример #49
0
def fuse_subpaths(path_node):
    """Fuse subpaths of a path. Should only be used on unstroked paths"""
    path_d = path_node.get("d", None)
    path = simplepath.parsePath(path_d)

    if len(path) == 0:
        return

    i = 0
    initial_point = [path[i][1][-2], path[i][1][-1]]
    return_stack = []
    while i < len(path):
        # Remove any terminators: they are redundant
        if path[i][0] == "Z":
            path.remove(["Z", []])
            continue

        # Skip all elements that do not begin a new path
        if i == 0 or path[i][0] != "M":
            i += 1
            continue

        # This element begins a new path - it should be a moveto
        assert (path[i][0] == 'M')

        # Swap it for a lineto
        path[i][0] = 'L'

        # If the old subpath has not been closed yet, close it
        if path[i - 1][1][-2] != initial_point[0] or path[
                i - 1][1][-2] != initial_point[1]:
            path.insert(i, ['L', initial_point])
            i += 1

        # Set the initial point of this subpath
        initial_point = [path[i - 1][1][-2], path[i - 1][1][-1]]

        # Append this point to the return stack
        return_stack.append(initial_point)
    #end while

    # Now pop the entire return stack
    while return_stack != []:
        el = ['L', return_stack.pop()]
        path.insert(i, el)
        i += 1

    path_d = simplepath.formatPath(path)
    path_node.set("d", path_d)
Пример #50
0
    def effect(self):
        zoom = self.options.zoom
        random.seed(self.options.seed)

        imagelist = randomize_input_string(self.options.text, zoom)
        image = layoutstring(imagelist, zoom)

        if image:
            s = {"stroke": "none", "fill": "#000000"}

            new = inkex.etree.Element(inkex.addNS("path", "svg"))
            new.set("style", simplestyle.formatStyle(s))

            new.set("d", simplepath.formatPath(image))
            self.current_layer.append(new)
Пример #51
0
def eliminarUltimoTrazo (letra) :
    d = letra.get('d')
    d = simplepath.formatPath( simplepath.parsePath(d) )
    dd=re.split(r'(i?)M',d)                                                            #Separa la cadena que le pases por los caracteres indicados en la 1 parte
    dd=filter(None, dd)                                                                #Crea una lista de elementos sin nulos, ni ceros
    for i, stri in enumerate(dd):
        dds=re.split(r'\s',stri)
        if 'L' in dds[-2]:#..yval..z last, ..yval..L..xval.. second last
            dds.pop()
            lastList=re.split(r'L',dds[-1])
            dds[-1]=lastList[0]
        dd[i]=' '.join(dds)
    d='M'+'M'.join(dd)

    letra.set('d',d)
    def effect(self):
        zoom = self.options.zoom
        random.seed(self.options.seed)

        imagelist = randomize_input_string(self.options.text, zoom)
        image = layoutstring(imagelist, zoom)

        if image:
            s = {'stroke': 'none', 'fill': '#000000'}

            new = inkex.etree.Element(inkex.addNS('path', 'svg'))
            new.set('style', simplestyle.formatStyle(s))

            new.set('d', simplepath.formatPath(image))
            self.current_layer.append(new)
	def effect(self):
		zoom = self.options.zoom
		random.seed(self.options.seed)

		imagelist = randomize_input_string(self.options.text, zoom)
		image = layoutstring( imagelist, zoom )

		if image:
			s = { 'stroke': 'none', 'fill': '#000000' }

			new = inkex.etree.Element(inkex.addNS('path','svg'))
			new.set('style', simplestyle.formatStyle(s))

			new.set('d', simplepath.formatPath(image))
			self.current_layer.append(new)
Пример #54
0
 def effect(self):
     for id, node in self.selected.iteritems():
         if node.tag == inkex.addNS('path','svg'):
             d = node.get('d')
             p = cubicsuperpath.parsePath(d)
             cspsubdiv.cspsubdiv(p, self.options.flat)
             np = []
             for sp in p:
                 first = True
                 for csp in sp:
                     cmd = 'L'
                     if first:
                         cmd = 'M'
                     first = False
                     np.append([cmd,[csp[1][0],csp[1][1]]])
                     node.set('d',simplepath.formatPath(np))
Пример #55
0
 def effect(self):
     for id, node in self.selected.iteritems():
         if node.tagName == 'path':
             d = node.attributes.getNamedItem('d')
             p = cubicsuperpath.parsePath(d.value)
             cspsubdiv.cspsubdiv(p, self.options.flat)
             np = []
             for sp in p:
                 first = True
                 for csp in sp:
                     cmd = 'L'
                     if first:
                         cmd = 'M'
                     first = False
                     np.append([cmd,[csp[1][0],csp[1][1]]])
                     d.value = simplepath.formatPath(np)
Пример #56
0
    def effect(self):
        for id, node in self.selected.iteritems():
            if node.tagName == 'rect':
                # create new path with basic dimensions of selected rectangle
                newpath = self.document.createElement('svg:path')
                x = float(node.attributes.getNamedItem('x').value)
                y = float(node.attributes.getNamedItem('y').value)
                w = float(node.attributes.getNamedItem('width').value)
                h = float(node.attributes.getNamedItem('height').value)

                #copy attributes of rect
                s = node.attributes.getNamedItem('style').value
                newpath.setAttribute('style', s)
                try:
                    t = node.attributes.getNamedItem('transform').value
                    newpath.setAttribute('transform', t)
                except AttributeError:
                    pass
                    
                # top and bottom where exchanhged
                newpath.setAttribute('d', simplepath.formatPath(
                            drawfunction(self.options.xstart,
                                self.options.xend,
                                self.options.ybottom,
                                self.options.ytop,
                                self.options.samples, 
                                w,h,x,y+h,
                                self.options.fofx, 
                                self.options.fpofx,
                                self.options.fponum,
                                self.options.times2pi,
                                self.options.isoscale,
                                self.options.drawaxis)))
                newpath.setAttribute('title', self.options.fofx)
                
                #newpath.setAttribute('desc', '!func;' + self.options.fofx + ';' 
                #                                      + self.options.fpofx + ';'
                #                                      + `self.options.fponum` + ';'
                #                                      + `self.options.xstart` + ';'
                #                                      + `self.options.xend` + ';'
                #                                      + `self.options.samples`)
                                
                # add path into SVG structure
                node.parentNode.appendChild(newpath)
                # option wether to remove the rectangle or not.
                if self.options.remove:
                  node.parentNode.removeChild(node)
Пример #57
0
    def fill_row(self, node):
        max_line_width = self.unittouu('450mm')

        x_gap = y_gap = self.unittouu('10mm')
        x_start = self.unittouu('3mm')
        y_start = self.unittouu('1600mm') - self.unittouu('3mm')

        total_width = 0
        total_height = self.total_height

        group = etree.SubElement(self.current_layer, addNS('g','svg'))

        bbox = computeBBox([node])
        x, _, y, _ = bbox
        node_width = x_gap + self.width(bbox)

        while total_width + node_width < max_line_width:
            node_copy = deepcopy(node)
            group.append(node_copy)

            x_dest = x_start + total_width
            y_dest = y_start - (total_height + self.height(bbox))

            # translation logic
            if node_copy.tag == addNS('path','svg'):
                x_delta = x_dest - x
                y_delta = y_dest - y

                path = parsePath(node_copy.attrib['d'])
                translatePath(path, x_delta, y_delta)
                node_copy.attrib['d'] = formatPath(path)
            elif node_copy.tag == addNS('g','svg'):
                x_delta = x_dest - x
                y_delta = y_dest - y

                translation_matrix = [[1.0, 0.0, x_delta], [0.0, 1.0, y_delta]]
                applyTransformToNode(translation_matrix, node_copy)

            else:
                node_copy.attrib['x'] = str(x_dest)
                node_copy.attrib['y'] = str(y_dest)

            total_width += node_width

        self.total_height += self.height(computeBBox(group)) + y_gap