コード例 #1
0
	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]
コード例 #2
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
コード例 #3
0
ファイル: cmyk.py プロジェクト: wout/Inkscape-OUTPUT-PRO
def representK(value):
    # returns CMS color if available
    if (re.search("icc-color", value.group()) ):
        return simplestyle.formatColor3f(float(1.00 - float(re.split('[,\)\s]+',value.group())[5])), float(1.00 - float(re.split('[,\)\s]+',value.group())[5])), float(1.00 - float(re.split('[,\)\s]+',value.group())[5])))
    else:
        red =   float(simplestyle.parseColor(str(value.group()))[0]/255.00)
        green = float(simplestyle.parseColor(str(value.group()))[1]/255.00)
        blue =  float(simplestyle.parseColor(str(value.group()))[2]/255.00)
        return simplestyle.formatColor3f(float(1.00 - calculateCMYK(red, green, blue)[3]), float(1.00 - calculateCMYK(red, green, blue)[3]), float(1.00 - calculateCMYK(red, green, blue)[3]))
コード例 #4
0
ファイル: export-pdf-cmyk.py プロジェクト: mptrsen/dotfiles
           def representK(value):
       # returns CMS color if available
               if ( re.search("icc-color", value.group()) ):
                   return simplestyle.formatColor3f(float(1.00 - float(re.split('[,\)\s]+',value.group())[5])), float(1.00 - float(re.split('[,\)\s]+',value.group())[5])), float(1.00 - float(re.split('[,\)\s]+',value.group())[5])))
 
               red =   float(simplestyle.parseColor(str(value.group()))[0]/255.00)
               green = float(simplestyle.parseColor(str(value.group()))[1]/255.00)
               blue =  float(simplestyle.parseColor(str(value.group()))[2]/255.00)
               return simplestyle.formatColor3f(float(1.00 - calculateCMYK(red, green, blue)[3]), float(1.00 - calculateCMYK(red, green, blue)[3]), float(1.00 - calculateCMYK(red, green, blue)[3]))
コード例 #5
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
コード例 #6
0
 def process_shape(self, node, mat):
     readStrokeWidth = not self.options.ignoreStrokeWidth
     color = None  # 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 !
     node_style = node.get('style')
     if node_style:
         style = self.groupstyle.copy()
         style.update(simplestyle.parseStyle(node_style))
         if style.has_key('stroke'):
             if style['stroke'] and style['stroke'] != 'none' and style[
                     'stroke'][0:3] != 'url':
                 rgb = simplestyle.parseColor(style['stroke'])
                 color = rgb[0] + 256 * rgb[1] + 256 * 256 * rgb[2]
         if readStrokeWidth and 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]
     if node.tag == inkex.addNS('path', 'svg'):
         d = node.get('d')
         if not d:
             self.not_converted.append(node.get('id'))
             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 = self.printer.rectangle_path(x, y, width, height)
     elif node.tag == inkex.addNS('defs', 'svg') or node.tag == inkex.addNS(
             'metadata', 'svg'):
         # ignore svg:defs and svg:metadata
         return
     elif node.tag.startswith('{' + inkex.NSS['svg']) == False:
         # ignore non-SVG elements
         return
     else:
         self.not_converted.append(node.get('id'))
         return
     trans = node.get('transform')
     if trans:
         mat = simpletransform.composeTransform(
             mat, simpletransform.parseTransform(trans))
     simpletransform.applyTransformToPath(mat, p)
     self.printer.draw_path(p, color, stroke, fillcolor)
コード例 #7
0
 def represent(value):
     red = float(
         simplestyle.parseColor(str(value.group()))[0] / 255.00)
     green = float(
         simplestyle.parseColor(str(value.group()))[1] / 255.00)
     blue = float(
         simplestyle.parseColor(str(value.group()))[2] / 255.00)
     return str(
         str(simplestyle.formatColor3f(red, green, blue)) +
         ' device-cmyk(' +
         str(calculateCMYK(red, green, blue)[0]) + ' ' +
         str(calculateCMYK(red, green, blue)[1]) + ' ' +
         str(calculateCMYK(red, green, blue)[2]) + ' ' +
         str(calculateCMYK(red, green, blue)[3]) + ')')
コード例 #8
0
ファイル: canvas.py プロジェクト: suman95/inkscape
 def getColor(self, rgb, a):
     r, g, b = simplestyle.parseColor(rgb)
     a = float(a)
     if a < 1:
         return "'rgba(%d, %d, %d, %.1f)'" % (r, g, b, a)
     else:
         return "'rgb(%d, %d, %d)'" % (r, g, b)
コード例 #9
0
    def matchStrokeColor(self, node, rgb, eps=None, avg=True):
        """
        Return True if the line color found in the style attribute of elem
        does not differ from rgb in any of the components more than eps.
        The default eps with avg=True is 64.
        With avg=False the default is eps=85 (33% on a 0..255 scale).

        In avg mode, the average of all three color channel differences is
        compared against eps. Otherwise each color channel difference is
        compared individually.

        The special cases None, False, True for rgb are interpreted logically.
        Otherwise rgb is expected as a list of three integers in 0..255 range.
        Missing style attribute or no stroke element is interpreted as False.
        Unparseable stroke elements are interpreted as 'black' (0,0,0).
        Hexadecimal stroke formats of '#RRGGBB' or '#RGB' are understood
        as well as 'rgb(100%, 0%, 0%) or 'red' relying on simplestyle.
        """
        if eps is None:
            eps = 64 if avg == True else 85
        if rgb is None or rgb is False: return False
        if rgb is True: return True
        style = self.getNodeStyle(node)
        s = style.get('stroke', '')
        if s == '': return False
        c = simplestyle.parseColor(s)
        if sum:
            s = abs(rgb[0] - c[0]) + abs(rgb[1] - c[1]) + abs(rgb[2] - c[2])
            if s < 3 * eps:
                return True
            return False
        if abs(rgb[0] - c[0]) > eps: return False
        if abs(rgb[1] - c[1]) > eps: return False
        if abs(rgb[2] - c[2]) > eps: return False
        return True
コード例 #10
0
ファイル: canvas.py プロジェクト: Spin0za/inkscape
 def getColor(self, rgb, a):
     r, g, b = simplestyle.parseColor(rgb)
     a = float(a)
     if a < 1:
         return "'rgba(%d, %d, %d, %.1f)'" % (r, g, b, a)
     else:
         return "'rgb(%d, %d, %d)'" % (r, g, b)
コード例 #11
0
    def _patches_to_segments(self, patches):
        stitches = patches_to_stitches(patches)

        segments = []

        last_pos = None
        last_color = None
        pen = None
        trimming = False

        for stitch in stitches:
            if stitch.trim:
                trimming = True
                last_pos = None
                continue

            if trimming:
                if stitch.jump:
                    continue
                else:
                    trimming = False

            pos = (stitch.x, stitch.y)

            if stitch.color == last_color:
                if last_pos:
                    segments.append(((last_pos, pos), pen))
            else:
                pen = self.color_to_pen(simplestyle.parseColor(stitch.color))

            last_pos = pos
            last_color = stitch.color

        return segments
コード例 #12
0
    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])
コード例 #13
0
ファイル: quasink.py プロジェクト: fabien/tcnc
 def parse_color(self, color_text):
     """Parse the color text input from the extension dialog."""
     try:
         if color_text and color_text.lower() != 'none':
             return simplestyle.formatColoria(simplestyle.parseColor(color_text))
     except:
         pass
     return 'none'
コード例 #14
0
 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
     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]])
コード例 #15
0
    def colorCercano(color, diferenciaMax):
        cercano = []
        rgb = simplestyle.parseColor('#' + color)
        for key, value in simplestyle.svgcolors.iteritems():

            rgbDiccionario = simplestyle.parseColor(value)
            diferencia = math.sqrt((rgbDiccionario[0] - rgb[0])**2 +
                                   (rgbDiccionario[1] - rgb[1])**2 +
                                   (rgbDiccionario[2] - rgb[2])**2)
            if diferencia < diferenciaMax:
                if cercano == []:
                    cercano.append(key)
                    cercano.append(diferencia)
                elif diferencia < cercano[1]:
                    cercano[0] = key
                    cercano[1] = diferencia

        if cercano == []:
            return None
        else:
            return cercano[0]
コード例 #16
0
    def test_simplestyle(self):
        """Test simplestyle API"""
        import simplestyle

        self.assertEqual(simplestyle.svgcolors['blue'], '#0000ff')
        self.assertEqual(simplestyle.parseStyle('foo: bar; abc-def: 123em'), {
            'foo': 'bar',
            'abc-def': '123em'
        })
        self.assertEqual(simplestyle.formatStyle({'foo': 'bar'}), 'foo:bar')
        self.assertTrue(simplestyle.isColor('#ff0000'))
        self.assertTrue(simplestyle.isColor('#f00'))
        self.assertTrue(simplestyle.isColor('blue'))
        self.assertFalse(simplestyle.isColor('none'))
        self.assertFalse(simplestyle.isColor('nosuchcolor'))
        self.assertEqual(simplestyle.parseColor('#0000ff'), (0, 0, 0xff))
        self.assertEqual(simplestyle.parseColor('red'), (0xff, 0, 0))
        self.assertEqual(simplestyle.formatColoria([0, 0x99, 0]), '#009900')
        self.assertEqual(simplestyle.formatColor3i(0, 0x99, 0), '#009900')
        self.assertEqual(simplestyle.formatColorfa([0, 1.0, 0]), '#00ff00')
        self.assertEqual(simplestyle.formatColor3f(0, 1.0, 0), '#00ff00')
コード例 #17
0
	def get_color(self, node):
		style = simplestyle.parseStyle(node.get("style"))
		color = None
		if style.has_key("stroke"):
			if simplestyle.isColor(style["stroke"]):
				color = "%02x%02x%02x" % (simplestyle.parseColor(style["stroke"]))
				if style.has_key("stroke-opacity"):
					alpha = float(style["stroke-opacity"])
					if alpha < 1:
						color = color + "%02x" % int(alpha * 255)

		return color
コード例 #18
0
 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]])
コード例 #19
0
ファイル: color.py プロジェクト: warewolf/inkstitch
    def __init__(self, color, name=None, number=None, manufacturer=None):
        if color is None:
            self.rgb = (0, 0, 0)
        elif isinstance(color, (list, tuple)):
            self.rgb = tuple(color)
        elif self.hex_str_re.match(color):
            self.rgb = simplestyle.parseColor(color)
        else:
            raise ValueError("Invalid color: " + repr(color))

        self.name = name
        self.number = number
        self.manufacturer = manufacturer
コード例 #20
0
ファイル: wcb_color.py プロジェクト: r3nder/wcb-ink
    def effect(self):

        self.layersProcessed = []
        self.paletteRGB = crayola_classic  #in the future: Offer additional choices

        for paintColor in self.paletteRGB:
            c = simplestyle.parseColor(paintColor)
            self.paletteYUV.append(self.rgbToYUV(c[0], c[1], c[2]))
            self.layerLabels.append("layerNotFound")

        self.scanForLayerNames(self.document.getroot(
        ))  #Recursively scan through document for named layers.
        #   		inkex.errormsg('layerLabels: ' + str(self.layerLabels))

        self.getAttribs(
            self.document.getroot()
        )  #Recursively scan through file, snap & label things that have color attributes.

        #If option is selected, try to move colors into layers.  Requires that everything is UNGROUPED first. :D
        if (self.options.snapLayers):
            #Now, walk through the palette, adding any new named layers that are needed
            for i in xrange(len(self.paletteRGB)):
                if (self.layerLabels[i] == "layerNotFound"):

                    # Create a group <g> element under the document root
                    layer = inkex.etree.SubElement(self.document.getroot(),
                                                   inkex.addNS('g', 'svg'))

                    # Add Inkscape layer attributes to this new group
                    layer.set(inkex.addNS('groupmode', 'inkscape'), 'layer')
                    layer.set(inkex.addNS('label', 'inkscape'),
                              crayola_classic_names[i])
                    self.layerLabels[i] = crayola_classic_names[i]

            for child in self.document.getroot():
                # 				inkex.errormsg('wcb-color-layer: ' + str(child.get('wcb-color-layer')))
                if (child.get(inkex.addNS(
                        'groupmode',
                        'inkscape')) == 'layer'):  #if it's a layer...
                    strLayerNameTmp = str(
                        child.get(inkex.addNS('label', 'inkscape')))
                    #  					inkex.errormsg('Layer Name: ' + strLayerNameTmp)
                    if (strLayerNameTmp in self.layerLabels):
                        #this is one of the named layers that we're using.
                        layerNumberInt = self.layerLabels.index(
                            strLayerNameTmp)
                        if not (strLayerNameTmp in self.layersProcessed):
                            self.layersProcessed.append(strLayerNameTmp)
                            # 	 	 					inkex.errormsg('Processed Layer Name: ' + strLayerNameTmp)
                            self.MoveColoredNodes(self.document.getroot(),
                                                  child, layerNumberInt)
コード例 #21
0
    def getLabelColour(self, nodeColour):
        labelColour = "#000000"

        try:
            nodeColour = simplestyle.parseColor(nodeColour)
            if sum(nodeColour) / len(nodeColour) < 128:
                labelColour = "#ffffff"
        except (
                TypeError,
                ZeroDivisionError  # if parseColor returns ""
        ):
            pass

        return labelColour
コード例 #22
0
ファイル: cmyk.py プロジェクト: brentini/Inkscape-OUTPUT-PRO
 def change_colors(origin, tipo_cor):
     for i in range(len(str(origin).split(tipo_cor + ':'))):
         if str(str(origin).split(tipo_cor + ':')[i].split(';')
                [0]) in simplestyle.svgcolors.keys():
             numeros_da_cor = simplestyle.formatColoria(
                 simplestyle.parseColor(
                     str(
                         str(origin).split(tipo_cor +
                                           ':')[i].split(';')[0])))
             origin = str(origin).replace(
                 ':' +
                 str(str(origin).split(tipo_cor + ':')[i].split(';')[0]) +
                 ';', ':' + numeros_da_cor + ';')
     return origin
コード例 #23
0
  def process_prop(self,col):
    #debug('got:'+col)
    if simplestyle.isColor(col):
      c=simplestyle.parseColor(col)
      col='#'+self.colmod(c[0],c[1],c[2])
      #debug('made:'+col)
    if col.startswith('url(#'):
	id = col[len('url(#'):col.find(')')]
	newid = '%s-%d' % (id, int(random.random() * 1000))
	#inkex.debug('ID:' + id )
	path = '//*[@id="%s"]' % id
	for node in xml.xpath.Evaluate(path,self.document):
	  self.process_gradient(node, newid)
	col = 'url(#%s)' % newid
    return col
コード例 #24
0
def extract_color(style, color_attrib, *opacity_attribs):
    if color_attrib in style.keys():
        if style[color_attrib] == "none":
            return [1, 1, 1, 0]
        c = simplestyle.parseColor(style[color_attrib])
    else:
        c = (0, 0, 0)

    # Convert color scales and adjust gamma
    color = [pow(c[0] / 255.0, sif.gamma), pow(c[1] / 255.0, sif.gamma), pow(c[2] / 255.0, sif.gamma), 1.0]

    for opacity in opacity_attribs:
        if opacity in style.keys():
            color[3] = color[3] * float(style[opacity])
    return color
コード例 #25
0
 def process_prop(self, col):
     #debug('got:'+col)
     if simplestyle.isColor(col):
         c = simplestyle.parseColor(col)
         col = '#' + self.colmod(c[0], c[1], c[2])
         #debug('made:'+col)
     if col.startswith('url(#'):
         id = col[len('url(#'):col.find(')')]
         newid = '%s-%d' % (id, int(random.random() * 1000))
         #inkex.debug('ID:' + id )
         path = '//*[@id="%s"]' % id
         for node in xml.xpath.Evaluate(path, self.document):
             self.process_gradient(node, newid)
         col = 'url(#%s)' % newid
     return col
コード例 #26
0
def process_prop(self, col, hsbcoeffs, hsbo_cf):
    #debug('got:'+col)
    if simplestyle.isColor(col):
        c = simplestyle.parseColor(col)
        col = '#' + colmod(c[0], c[1], c[2], hsbcoeffs, hsbo_cf)
        #debug('made:'+col)
    if col.startswith('url(#'):
        id = col[len('url(#'):col.find(')')]
        newid = self.newid(self.svg_prefixfromtag(id))
        #inkex.debug('ID:' + id )
        path = '//*[@id="%s"]' % id
        for node in self.document.xpath(path, namespaces=inkex.NSS):
            process_gradient(self, node, newid, hsbcoeffs)
        col = 'url(#%s)' % newid
    return col
コード例 #27
0
ファイル: wcb_color.py プロジェクト: brucetsao/wcb-ink
	def process_prop(self,col):
		#debug('got:'+col)
		if simplestyle.isColor(col):
			c=simplestyle.parseColor(col)
			col='#'+self.colmod(c[0],c[1],c[2])
			#debug('made:'+col)
# 		if col.startswith('url(#'):
# 			id = col[len('url(#'):col.find(')')]
# 			newid = '%s-%d' % (id, int(random.random() * 1000))
# 			#inkex.debug('ID:' + id )
# 			path = '//*[@id="%s"]' % id
# 			for node in self.document.xpath(path, namespaces=inkex.NSS):
# 				self.process_gradient(node, newid)
# 			col = 'url(#%s)' % newid
		return col				
コード例 #28
0
ファイル: stylevariation.py プロジェクト: Alpt/gdadin
def process_prop(self, col, hsbcoeffs, hsbo_cf):
  #debug('got:'+col)
  if simplestyle.isColor(col):
    c=simplestyle.parseColor(col)
    col='#'+colmod(c[0],c[1],c[2], hsbcoeffs, hsbo_cf)
    #debug('made:'+col)
  if col.startswith('url(#'):
    id = col[len('url(#'):col.find(')')]
    newid = self.newid(self.svg_prefixfromtag(id))
    #inkex.debug('ID:' + id )
    path = '//*[@id="%s"]' % id
    for node in self.document.xpath(path, namespaces=inkex.NSS):
      process_gradient(self, node, newid, hsbcoeffs)
    col = 'url(#%s)' % newid
  return col
コード例 #29
0
    def get_color(self, element):
        if element.tag == inkex.addNS('g', 'svg'):
            # Sometimes Inkscape sets a stroke style on a group, which seems to
            # have no visual effect.  If we didn't ignore those, we'd cut those
            # objects twice.
            return None

        color = self.get_style(element).get('stroke', 'none')

        if color == 'none':
            color = self.get_style(element).get('fill', 'none')

        if color != 'none':
            return simplestyle.parseColor(color)
        else:
            return None
コード例 #30
0
ファイル: wcb_color.py プロジェクト: r3nder/wcb-ink
    def process_prop(self, col):
        #debug('got:'+col)
        if simplestyle.isColor(col):
            c = simplestyle.parseColor(col)
            col = '#' + self.colmod(c[0], c[1], c[2])
            #debug('made:'+col)


# 		if col.startswith('url(#'):
# 			id = col[len('url(#'):col.find(')')]
# 			newid = '%s-%d' % (id, int(random.random() * 1000))
# 			#inkex.debug('ID:' + id )
# 			path = '//*[@id="%s"]' % id
# 			for node in self.document.xpath(path, namespaces=inkex.NSS):
# 				self.process_gradient(node, newid)
# 			col = 'url(#%s)' % newid
        return col
コード例 #31
0
    def get_color(self, element):
        if (element.tag == inkex.addNS('g', 'svg')
                or element.tag == inkex.addNS('svg', 'svg')):
            # Make sure we don't report a color on a group or on the svg as a whole
            # (to avoid duplicate cutting)
            return None

        color = self.get_style(element).get('stroke', 'colorless')

        if color == 'colorless':
            color = self.get_style(element).get('fill', 'colorless')

        if color != 'colorless':
            if hasattr(inkex, 'Color'):
                color = inkex.Color(color).to_rgb()  # inkscape >= 1.0
            else:
                color = simplestyle.parseColor(color)  # inkscape < 1.0
        return color
コード例 #32
0
ファイル: wcb_color.py プロジェクト: brucetsao/wcb-ink
	def effect(self):
		
		self.layersProcessed = []
		self.paletteRGB = crayola_classic	#in the future: Offer additional choices
		

		for paintColor in self.paletteRGB: 
			c = simplestyle.parseColor(paintColor) 
			self.paletteYUV.append(self.rgbToYUV(c[0], c[1], c[2]))	
			self.layerLabels.append("layerNotFound")
			
		self.scanForLayerNames(self.document.getroot())	#Recursively scan through document for named layers.
#   		inkex.errormsg('layerLabels: ' + str(self.layerLabels)) 

		self.getAttribs(self.document.getroot())	#Recursively scan through file, snap & label things that have color attributes.



		#If option is selected, try to move colors into layers.  Requires that everything is UNGROUPED first. :D
 		if (self.options.snapLayers):
			#Now, walk through the palette, adding any new named layers that are needed
			for i in xrange(len(self.paletteRGB)):
				if (self.layerLabels[i] == "layerNotFound"):	
			
					# Create a group <g> element under the document root
					layer = inkex.etree.SubElement( self.document.getroot(), inkex.addNS( 'g', 'svg' ) )
		
					# Add Inkscape layer attributes to this new group
					layer.set( inkex.addNS('groupmode', 'inkscape' ), 'layer' )
					layer.set( inkex.addNS( 'label', 'inkscape' ), crayola_classic_names[i] )
					self.layerLabels[i] = crayola_classic_names[i]

			for child in self.document.getroot():
# 				inkex.errormsg('wcb-color-layer: ' + str(child.get('wcb-color-layer'))) 
				if ( child.get( inkex.addNS( 'groupmode', 'inkscape' ) ) == 'layer' ): 		#if it's a layer...	
					strLayerNameTmp = str(child.get(inkex.addNS( 'label', 'inkscape' )))
#  					inkex.errormsg('Layer Name: ' + strLayerNameTmp)
					if (strLayerNameTmp in self.layerLabels):
						#this is one of the named layers that we're using.
						layerNumberInt = self.layerLabels.index(strLayerNameTmp)
						if not (strLayerNameTmp in self.layersProcessed):
							self.layersProcessed.append(strLayerNameTmp)
# 	 	 					inkex.errormsg('Processed Layer Name: ' + strLayerNameTmp)
 	 						self.MoveColoredNodes(self.document.getroot(), child, layerNumberInt)
コード例 #33
0
ファイル: color.py プロジェクト: zgyarmati/inkstitch
    def __init__(self, color, name=None, number=None, manufacturer=None):
        if color is None:
            self.rgb = (0, 0, 0)
        elif isinstance(color, EmbThread):
            self.name = color.description
            self.number = color.catalog_number
            self.manufacturer = color.brand
            self.rgb = (color.get_red(), color.get_green(), color.get_blue())
            return
        elif isinstance(color, (list, tuple)):
            self.rgb = tuple(color)
        elif self.hex_str_re.match(color):
            self.rgb = simplestyle.parseColor(color)
        else:
            raise ValueError("Invalid color: " + repr(color))

        self.name = name
        self.number = number
        self.manufacturer = manufacturer
コード例 #34
0
 def process_prop(self, col):
   #inkex.debug('got:'+col+str(type(col)))
   if simplestyle.isColor(col):
     c=simplestyle.parseColor(col)
     col='#'+self.colmod(c[0], c[1], c[2])
     #inkex.debug('made:'+col)
   elif col.startswith('url(#'):
     id = col[len('url(#'):col.find(')')]
     newid = '%s-%d' % (id, int(random.random() * 1000))
     #inkex.debug('ID:' + id )
     path = '//*[@id="%s"]' % id
     for node in self.document.xpath(path, namespaces=inkex.NSS):
       self.process_gradient(node, newid)
     col = 'url(#%s)' % newid
   # what remains should be opacity
   else:
     col = self.opacmod(col)
     
   #inkex.debug('col:'+str(col))
   return col
コード例 #35
0
    def _patches_to_segments(self, patches):
        stitches = patches_to_stitches(patches)

        segments = []

        last_pos = None
        last_color = None
        pen = None

        for stitch in stitches:
            pos = (stitch.x, stitch.y)

            if stitch.color == last_color:
                segments.append(((last_pos, pos), pen))
            else:
                pen = self.color_to_pen(simplestyle.parseColor(stitch.color))

            last_pos = pos
            last_color = stitch.color

        return segments
コード例 #36
0
    def getNodeAndLabelColourForGradient(self, gradientNode):
        stops = self.getGradientStops(gradientNode)

        nodeColours = []

        for stop in stops:
            offset = float(stop[0])
            colour = stop[1]
            nodeColours.append("{colour:s}{offset:s}".format(
                colour=colour,
                offset="" if offset in (0,
                                        1) else " ({:0.2f})".format(offset)))
        nodeColour = u" ↔ ".join(nodeColours)

        avgNodeColour = [
            sum([simplestyle.parseColor(stop[1])[c]
                 for stop in stops]) / len(stops) for c in range(3)
        ]

        labelColour = \
            self.getLabelColour(simplestyle.formatColoria(avgNodeColour))

        return (nodeColour, labelColour)
コード例 #37
0
 def process_path(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':
                 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.color = 7  # default is black
     if hsl[2]:
         self.color = 1 + (int(6 * hsl[0] + 0.5) % 6)  # use 6 hues
     d = node.get('d')
     if d:
         p = cubicsuperpath.parsePath(d)
         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]])
コード例 #38
0
def addColor(col):
    if simplestyle.isColor(col):
        c = simplestyle.parseColor(col)
        colors["%3i %3i %3i " % (c[0], c[1], c[2])] = simplestyle.formatColoria(c).upper()
コード例 #39
0
ファイル: cmyk.py プロジェクト: jonata/Inkscape-OUTPUT-PRO
 def change_colors(origin, tipo_cor):
     for i in range(len(str(origin).split(tipo_cor + ':'))):
         if str(str(origin).split(tipo_cor + ':')[i].split(';')[0]) in simplestyle.svgcolors.keys():
             numeros_da_cor = simplestyle.formatColoria(simplestyle.parseColor(str(str(origin).split(tipo_cor + ':')[i].split(';')[0])))
             origin = str(origin).replace(':' + str(str(origin).split(tipo_cor + ':')[i].split(';')[0]) + ';', ':' + numeros_da_cor + ';')
     return origin
コード例 #40
0
ファイル: export-pdf-cmyk.py プロジェクト: mptrsen/dotfiles
 def represent(value):
     red =   float(simplestyle.parseColor(str(value.group()))[0]/255.00)
     green = float(simplestyle.parseColor(str(value.group()))[1]/255.00)
     blue =  float(simplestyle.parseColor(str(value.group()))[2]/255.00)
     return str(str(simplestyle.formatColor3f(red,green,blue)) + ' device-cmyk(' + str(calculateCMYK(red, green, blue)[0]) + ' ' + str(calculateCMYK(red, green, blue)[1]) + ' ' + str(calculateCMYK(red, green, blue)[2]) + ' ' + str(calculateCMYK(red, green, blue)[3]) + ')')
コード例 #41
0
    def process_shape(self, node, mat, group_stroke = None):
        #################################
        ### Determine the shape type  ###
        #################################
        try:
            i = node.tag.find('}')
            if i >= 0:
                tag_type = node.tag[i+1:]
        except:
            tag_type=""
        
        ##############################################
        ### Set a unique identifier for each shape ###
        ##############################################
        self.id_cnt=self.id_cnt+1
        path_id = "ID%d"%(self.id_cnt)
        sw_flag = False
        changed = False
        #######################################
        ### Handle references to CSS data   ###
        #######################################
        class_val = node.get('class')
        if class_val:
            css_data = ""
            for cv in class_val.split(' '):
                if css_data!="":
                    css_data = self.CSS_values.get_css_value(tag_type,cv)+";"+css_data
                else:
                    css_data = self.CSS_values.get_css_value(tag_type,cv)
                
            # Remove the reference to the CSS data 
            del node.attrib['class']

            # Check if a style entry already exists. If it does
            # append the the existing style data to the CSS data
            # otherwise create a new style entry.
            if node.get('style'):
                if css_data!="":
                    css_data = css_data + ";" + node.get('style')
                    node.set('style', css_data)
            else:
                node.set('style', css_data)

        style   = node.get('style')
        self.Cut_Type[path_id]="raster" # Set default type to raster

        text_message_warning = "SVG File with Color Coded Text Outlines Found: (i.e. Blue: engrave/ Red: cut)"
        line1 = "SVG File with color coded text outlines found (i.e. Blue: engrave/ Red: cut)."
        line2 = "Automatic conversion to paths failed: Try upgrading to Inkscape .90 or later"
        line3 = "To convert manually in Inkscape: select the text then select \"Path\"-\"Object to Path\" in the menu bar."
        text_message_fatal  = "%s\n\n%s\n\n%s" %(line1,line2,line3)
        
        ##############################################
        ### Handle 'style' data outside of style   ###
        ##############################################
        stroke_outside = node.get('stroke')
        if not stroke_outside:
            stroke_outside = group_stroke
        if stroke_outside:
            stroke_width_outside = node.get('stroke-width')
            
            col = stroke_outside
            col= col.strip()
            if simplestyle.isColor(col):
                c=simplestyle.parseColor(col)
                (new_val,changed,k40_action)=self.colmod(c[0],c[1],c[2],path_id)
            else:
                new_val = col
            if changed:
                node.set('stroke',new_val)
                node.set('stroke-width',"0.0")
                node.set('k40_action', k40_action)
                sw_flag = True

            if sw_flag == True:
                if node.tag == inkex.addNS('text','svg') or node.tag == inkex.addNS('flowRoot','svg'):
                    if (self.txt2paths==False):
                        raise SVG_TEXT_EXCEPTION(text_message_warning)
                    else:
                        raise Exception(text_message_fatal)

        ###################################################
        ### Handle 'k40_action' data outside of style   ###
        ###################################################
        if node.get('k40_action'):
            k40_action = node.get('k40_action')
            changed=True
            self.Cut_Type[path_id]=k40_action

        ##############################################
        ### Handle 'style' data                    ###
        ##############################################
        if style:
            declarations = style.split(';')
            i_sw = -1
            
            sw_prop = 'stroke-width'
            for i,decl in enumerate(declarations):
                parts = decl.split(':', 2)
                if len(parts) == 2:
                    (prop, col) = parts
                    prop = prop.strip().lower()
                    
                    if prop == 'k40_action':
                        changed = True
                        self.Cut_Type[path_id]=col
                        
                    #if prop in color_props:
                    if prop == sw_prop:
                        i_sw = i
                    if prop == 'stroke':
                        col= col.strip()
                        if simplestyle.isColor(col):
                            c=simplestyle.parseColor(col)
                            (new_val,changed,k40_action)=self.colmod(c[0],c[1],c[2],path_id)
                        else:
                            new_val = col
                        if changed:
                            declarations[i] = prop + ':' + new_val
                            declarations.append('k40_action' + ':' + k40_action)
                            sw_flag = True
            if sw_flag == True:
                if node.tag == inkex.addNS('text','svg') or node.tag == inkex.addNS('flowRoot','svg'):
                    if (self.txt2paths==False):
                        raise SVG_TEXT_EXCEPTION(text_message_warning)
                    else:
                        raise Exception(text_message_fatal)

                if i_sw != -1:
                    declarations[i_sw] = sw_prop + ':' + "0.0"
                else:
                    declarations.append(sw_prop + ':' + "0.0")
            node.set('style', ';'.join(declarations))
        ##############################################

        #####################################################
        ### If vector data was found save the path data   ###
        #####################################################
        if changed:
            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'))
                rx = 0.0
                ry = 0.0
                if node.get('rx'):
                    rx=float(node.get('rx'))
                if node.get('ry'):
                    ry=float(node.get('ry'))
                    
                if max(rx,ry) > 0.0:
                    if rx==0.0 or ry==0.0:
                        rx = max(rx,ry)
                        ry = rx
                    Rxmax = abs(width)/2.0
                    Rymax = abs(height)/2.0
                    rx = min(rx,Rxmax)
                    ry = min(ry,Rymax)
                    L1 = "M %f,%f %f,%f "      %(x+rx       , y          , x+width-rx , y          )
                    C1 = "A %f,%f 0 0 1 %f,%f" %(rx         , ry         , x+width    , y+ry       )
                    L2 = "M %f,%f %f,%f "      %(x+width    , y+ry       , x+width    , y+height-ry)
                    C2 = "A %f,%f 0 0 1 %f,%f" %(rx         , ry         , x+width-rx , y+height   )
                    L3 = "M %f,%f %f,%f "      %(x+width-rx , y+height   , x+rx       , y+height   )
                    C3 = "A %f,%f 0 0 1 %f,%f" %(rx         , ry         , x          , y+height-ry)
                    L4 = "M %f,%f %f,%f "      %(x          , y+height-ry, x          , y+ry       )
                    C4 = "A %f,%f 0 0 1 %f,%f" %(rx         , ry         , x+rx       , y          )
                    d =  L1 + C1 + L2 + C2 + L3 + C3 + L4 + C4    
                else:
                    d = "M %f,%f %f,%f %f,%f %f,%f Z" %(x,y, x+width,y,  x+width,y+height, x,y+height) 
                p = cubicsuperpath.parsePath(d)
                
            elif node.tag == inkex.addNS('circle','svg'):
                cx = float(node.get('cx') )
                cy = float(node.get('cy'))
                r  = float(node.get('r'))
                d  = "M %f,%f A   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f Z" %(cx+r,cy, r,r,cx,cy+r,  r,r,cx-r,cy,  r,r,cx,cy-r, r,r,cx+r,cy)
                p = cubicsuperpath.parsePath(d)
            
            elif node.tag == inkex.addNS('ellipse','svg'):
                cx = float(node.get('cx')) 
                cy = float(node.get('cy'))
                if node.get('r'):
                    r = float(node.get('r'))
                    rx = r
                    ry = r
                if node.get('rx'):
                    rx = float(node.get('rx'))
                if node.get('ry'):
                    ry = float(node.get('ry'))
                    
                d  = "M %f,%f A   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f Z" %(cx+rx,cy, rx,ry,cx,cy+ry,  rx,ry,cx-rx,cy,  rx,ry,cx,cy-ry, rx,ry,cx+rx,cy)
                p = cubicsuperpath.parsePath(d)
                
            elif (node.tag == inkex.addNS('polygon','svg')) or (node.tag == inkex.addNS('polyline','svg')):
                points = node.get('points')
                if not points:
                    return
               
                points = points.replace(',', ' ')
                while points.find('  ') > -1:
                    points = points.replace('  ', ' ')
                    
                points = points.strip().split(" ")
                d = "M "
                for i in range(0,len(points),2):
                    x = float(points[i])
                    y = float(points[i+1])
                    d = d + "%f,%f " %(x,y)

                #Close the loop if it is a ploygon
                if node.tag == inkex.addNS('polygon','svg'):
                    d = d + "Z"
                p = cubicsuperpath.parsePath(d)

            elif node.tag == inkex.addNS('line','svg'):
                x1 = float(node.get('x1')) 
                y1 = float(node.get('y1'))
                x2 = float(node.get('x2'))
                y2 = float(node.get('y2'))
                d = "M "
                d = "M %f,%f %f,%f" %(x1,y1,x2,y2)
                p = cubicsuperpath.parsePath(d)          
            else:
                #print("something was ignored")
                #print(node.tag)
                return
            
            trans = node.get('transform')
            if trans:
                mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
            simpletransform.applyTransformToPath(mat, p)
            
            ##########################################
            ## Break Curves down into small lines  ###
            ##########################################
            f = self.flatness
            is_flat = 0
            while is_flat < 1:
                try:
                    cspsubdiv.cspsubdiv(p, f)
                    is_flat = 1
                except IndexError:
                    break
                except:
                    f += 0.1
                    if f>2 :
                      break
                      #something has gone very wrong.
            ##########################################
            rgb=(0,0,0)
            for sub in p:
                for i in range(len(sub)-1):
                    x1 = sub[i][1][0]
                    y1 = sub[i][1][1]
                    x2 = sub[i+1][1][0]
                    y2 = sub[i+1][1][1]
                    self.lines.append([x1,y1,x2,y2,rgb,path_id])
コード例 #42
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_rgbcolorpercent(self):
     "Parse 'rgb(100%,100%,100%)'"
     col = parseColor("rgb(100%,100%,100%)")
     self.failUnlessEqual((255, 255, 255), col)
コード例 #43
0
ファイル: openscad_dxf.py プロジェクト: pauek/CookieCutters
    def effect(self):
        object2path.ObjectToPath.effect(self)
        self.dxf += self.dxf_add_codes([('999', 'Inkscape export via OpenSCAD DXF Export')])
        self.dxf += dxf_templates.r14_header
        
        scale = 25.4/90.0
        h = self.unittouu(self.document.getroot().xpath('@height',namespaces=inkex.NSS)[0])

        path = '//svg:path'
        pm = pathmodifier.PathModifier()
        layers = []
        dxf_body = ''
        for node in self.document.getroot().xpath(path,namespaces=inkex.NSS):
            pm.objectToPath(node, True)
            layer = node.getparent().get(inkex.addNS('label', 'inkscape'))
            if layer == None:
                layer = 'Layer 1'
            layer = layer.replace(' ', '_')

            if layer not in layers:
                layers.append(layer)
                self.layer_dims[layer] = {
                    'minX':None,
                    'minY':None,
                    'maxX':None,
                    'maxY':None
                }

            d = node.get('d')
            color = (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':
                        color = simplestyle.parseColor(style['stroke'])

            p = cubicsuperpath.parsePath(d)
            
            t = node.get('transform')
            if t != None:
                m = simpletransform.parseTransform(t)
                simpletransform.applyTransformToPath(m,p)
            
            m = [[scale,0,0],[0,-scale,h*scale]]
            simpletransform.applyTransformToPath(m,p)

            dxf_body += self.dxf_path_to_lines(layer, p, color)

        self.dxf += self.dxf_add_codes([
            ('0', 'TABLE'),
            ('2', 'LAYER'),
            ('5', '2'),
            ('330', '0'),
            ('100', 'AcDbSymbolTable'),
            # group code 70 tells a reader how many table records to expect (e.g. pre-allocate memory for).
            # It must be greater or equal to the actual number of records
            ('70', str(len(layers)))
        ])

        # Add dimensions for total width and height
        dxf_dims = self.dxf_add_dimension('total_width', 
            [self.global_dims['minX'], self.global_dims['maxX']])
        dxf_dims += self.dxf_add_dimension('total_height', 
            None, [self.global_dims['minY'], self.global_dims['maxY']])
        for layer in layers:
            self.dxf += self.dxf_add_codes([
                ('0', 'LAYER'),
                ('5', '10'),
                ('330', '2'),
                ('100', 'AcDbSymbolTableRecord'),
                ('100', 'AcDbLayerTableRecord'),
                ('2', layer),
                ('70', '0'),
                ('62', '7'),
                ('6', 'CONTINUOUS')
            ])
            # Add dimensions for layer width and height
            dxf_dims += self.dxf_add_dimension(layer + '_width', 
                [self.layer_dims[layer]['minX'], self.layer_dims[layer]['maxX']], None, layer)
            dxf_dims += self.dxf_add_dimension(layer + '_height', 
                None, [self.layer_dims[layer]['minY'], self.layer_dims[layer]['maxY']], layer)

        self.dxf += self.dxf_add_codes([
            ('0', 'ENDTAB'),
            ('0', 'ENDSEC')
        ])

        self.dxf += dxf_templates.r14_style
        self.dxf += dxf_dims
        self.dxf += dxf_body

        self.dxf += dxf_templates.r14_footer
コード例 #44
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_hexcolor3digit(self):
     "Parse '#fff'"
     col = parseColor("#fff")
     self.failUnlessEqual((255, 255, 255), col)
コード例 #45
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_rgbcolorint(self):
     "Parse 'rgb(255,255,255)'"
     col = parseColor("rgb(255,255,255)")
     self.failUnlessEqual((255, 255, 255), col)
コード例 #46
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_hexcolor4digit(self):
     "Parse '#ff0102'"
     col = parseColor("#ff0102")
     self.failUnlessEqual((255, 1, 2), col)
コード例 #47
0
    def process_shape(self, node, mat):
        nodetype = node.get(inkex.addNS("type","sodipodi"))
        if nodetype == "arc":
            # These are actually only used for checking the maths
            ui_arc = True
            ui_cx = float(node.get(inkex.addNS('cx','sodipodi')))
            ui_cy = float(node.get(inkex.addNS('cy','sodipodi')))
            ui_r = float(node.get(inkex.addNS('r','sodipodi'),0.0))
            ui_rx = float(node.get(inkex.addNS('rx','sodipodi'),ui_r))
            ui_ry = float(node.get(inkex.addNS('ry','sodipodi'),ui_r))
            ui_a0 = float(node.get(inkex.addNS('start','sodipodi'),0))
            ui_a1 = float(node.get(inkex.addNS('end','sodipodi'),2*math.pi))
        else:
            ui_arc = False

        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
        trans = node.get('transform')
        if trans:
            mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
        if node.tag == inkex.addNS('path','svg'):
            d = node.get('d')
            if not d:
                inkex.errormsg("PATH DATA MISSING!")
                inkex.sys.exit()
                return
            # Filter out any eliptical arcs for special treatment:
            simplep = simplepath.parsePath(d)
            split = split_arc_nonarc(simplep)
            arc_simplep = split[1]
            simplep = split[0]
            if len(simplep)>0:
                if (simplep[-1][0] == 'z' or simplep[-1][0] == 'Z'):
                    self.closed = 1
                p = cubicsuperpath.CubicSuperPath(simplep)
                if (self.options.FLATTENBES):
                    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]]])
                    p = cubicsuperpath.parsePath(simplepath.formatPath(np))
                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]])

            # Now process any arc segments:

            if len(arc_simplep) > 0:

                # As our path is broken by arcs, we cannot have a closed polyline:
                self.closed = 0

                i = 0
                while i < len(arc_simplep):
                    cmd, params = arc_simplep[i]
                    if cmd == 'M':
                        p0 = params[:]
                    else:
                        p1 = params[-2:]
                        rx,ry,theta,largearc,sweep = params[0:5]
                        e_params = convert_arc_abrxry0_to_crxry00102(p0,p1,rx,ry,theta,largearc==1,sweep==1)
                        cx,cy = e_params[0]
                        if (i<len(arc_simplep)-1):
                            cmd2, params2 = arc_simplep[i+1]
                        else:
                            cmd2 = '-'
                        if cmd2 == 'A' and params2[0:5] == params[0:5] and params2[-2:] == p0:
                            # complete circle or ellipse
                            a0 = 0
                            a1 = 2.0*math.pi
                            i = i + 1
                            p1 = p0
                        else:
                            a0 = e_params[4]
                            a1 = e_params[5]
                            p0 = p1
                        self.dxf_arc_transform(mat,cx,cy,rx,ry,theta,a0,a1)
                        # check did we get our maths right?
                        if ui_arc and ((abs(cx - ui_cx) > 0.05) or (abs(cy - ui_cy) > 0.05) or (abs(a0 - ui_a0)>0.1) or (abs(a1 - ui_a1)>0.1)):
                            inkex.errormsg("WARNING, Maths failure. Stored attributes of arc and calculated values do not agree!:")
                            inkex.errormsg("sodipodi:\tc=[%f,%f],r=[%f,%f],a0=%fpi,a1=%fpi" % (ui_cx,ui_cy,ui_rx,ui_ry,ui_a0/math.pi,ui_a1/math.pi))
                            inkex.errormsg("raw:\tc=[%f,%f],r=[%f,%f],a0=%fpi,a1=%fpi" % (cx,cy,rx,ry,a0/math.pi,a1/math.pi))
                    i = i+1

                return
        elif node.tag in [ inkex.addNS('circle','svg'), 'circle', \
                            inkex.addNS('ellipse','svg'), 'ellipse' ]:
                cx = float(node.get('cx',0))
                cy = float(node.get('cy',0))
                if node.tag == inkex.addNS('circle','svg'):
                    rx = float(node.get('r',0))
                    ry = rx
                else:
                    rx = float(node.get('rx',0))
                    ry = float(node.get('ry',rx))
                a0 = 0.0
                a1 = 2*math.pi
                self.dxf_arc_transform(mat,cx,cy,rx,ry,0,a0,a1)
                return
        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'))
            pt0 = [x,y]
            pt1 = [x + width, y]
            pt2 = [x + width, y + height]
            pt3 = [x, y + height]
            simpletransform.applyTransformToPoint(mat,pt0)
            simpletransform.applyTransformToPoint(mat,pt1)
            simpletransform.applyTransformToPoint(mat,pt2)
            simpletransform.applyTransformToPoint(mat,pt3)
            if (self.options.POLY == 'true'):
                self.LWPOLY_line([pt0,pt1])
                self.LWPOLY_line([pt1,pt2])
                self.LWPOLY_line([pt2,pt3])
                self.LWPOLY_line([pt3,pt0])
            else:
                self.dxf_line([pt0,pt1])
                self.dxf_line([pt1,pt2])
                self.dxf_line([pt2,pt3])
                self.dxf_line([pt3,pt0])
            return
        else:
            return
コード例 #48
0
 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.color = 7  # default is black
     if hsl[2]:
         self.color = 1 + (int(6 * hsl[0] + 0.5) % 6)  # use 6 hues
     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', 0))
         y = float(node.get('y', 0))
         width = float(node.get('width'))
         height = float(node.get('height'))
         d = "m %s,%s %s,%s %s,%s %s,%s z" % (x, y, width, 0, 0, height,
                                              -width, 0)
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('line', 'svg'):
         x1 = float(node.get('x1', 0))
         x2 = float(node.get('x2', 0))
         y1 = float(node.get('y1', 0))
         y2 = float(node.get('y2', 0))
         d = "M %s,%s L %s,%s" % (x1, y1, x2, y2)
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('circle', 'svg'):
         cx = float(node.get('cx', 0))
         cy = float(node.get('cy', 0))
         r = float(node.get('r'))
         d = "m %s,%s a %s,%s 0 0 1 %s,%s %s,%s 0 0 1 %s,%s z" % (
             cx + r, cy, r, r, -2 * r, 0, r, r, 2 * r, 0)
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('ellipse', 'svg'):
         cx = float(node.get('cx', 0))
         cy = float(node.get('cy', 0))
         rx = float(node.get('rx'))
         ry = float(node.get('ry'))
         d = "m %s,%s a %s,%s 0 0 1 %s,%s %s,%s 0 0 1 %s,%s z" % (
             cx + rx, cy, rx, ry, -2 * rx, 0, rx, ry, 2 * rx, 0)
         p = cubicsuperpath.parsePath(d)
     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]])
コード例 #49
0
    def process_shape(self, node, mat):
        rgb = (0, 0, 0)
        path_id = node.get('id')
        style = node.get('style')
        self.Cut_Type[path_id] = "raster"  # Set default type to raster

        #color_props_fill = ('fill', 'stop-color', 'flood-color', 'lighting-color')
        #color_props_stroke = ('stroke',)
        #color_props = color_props_fill + color_props_stroke

        #####################################################
        ## The following is ripped off from Coloreffect.py ##
        #####################################################
        if style:
            declarations = style.split(';')
            i_sw = -1
            sw_flag = False
            sw_prop = 'stroke-width'
            for i, decl in enumerate(declarations):
                parts = decl.split(':', 2)
                if len(parts) == 2:
                    (prop, col) = parts
                    prop = prop.strip().lower()
                    #if prop in color_props:
                    if prop == sw_prop:
                        i_sw = i
                    if prop == 'stroke':
                        col = col.strip()
                        if simplestyle.isColor(col):
                            c = simplestyle.parseColor(col)
                            new_val = '#' + self.colmod(
                                c[0], c[1], c[2], path_id)
                        else:
                            new_val = col
                        if new_val != col:
                            declarations[i] = prop + ':' + new_val
                            sw_flag = True
            if sw_flag == True:
                if node.tag == inkex.addNS('text', 'svg'):
                    if (self.txt2paths == False):
                        raise SVG_TEXT_EXCEPTION(
                            "SVG File with Color Coded Text Outlines Found: (i.e. Blue: engrave/ Red: cut)"
                        )
                    else:
                        line1 = "SVG File with color coded text outlines found (i.e. Blue: engrave/ Red: cut)."
                        line2 = "Automatic conversion to paths failed: Try upgrading to Inkscape .90 or later"
                        line3 = "To convert manually in Inkscape: select the text then select \"Path\"-\"Object to Path\" in the menu bar."

                        raise StandardError("%s\n\n%s\n\n%s" %
                                            (line1, line2, line3))

                if i_sw != -1:
                    declarations[i_sw] = sw_prop + ':' + "0.0"
                else:
                    declarations.append(sw_prop + ':' + "0.0")
            node.set('style', ';'.join(declarations))

        #####################################################
        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'))
            #d = "M %f,%f %f,%f %f,%f %f,%f Z" %(x,y, x+width,y,  x+width,y+height, x,y+height)
            #p = cubicsuperpath.parsePath(d)
            rx = 0.0
            ry = 0.0
            if node.get('rx'):
                rx = float(node.get('rx'))
            if node.get('ry'):
                ry = float(node.get('ry'))

            if max(rx, ry) > 0.0:
                if rx == 0.0 or ry == 0.0:
                    rx = max(rx, ry)
                    ry = rx
                L1 = "M %f,%f %f,%f " % (x + rx, y, x + width - rx, y)
                C1 = "A %f,%f 0 0 1 %f,%f" % (rx, ry, x + width, y + ry)
                L2 = "M %f,%f %f,%f " % (x + width, y + ry, x + width,
                                         y + height - ry)
                C2 = "A %f,%f 0 0 1 %f,%f" % (rx, ry, x + width - rx,
                                              y + height)
                L3 = "M %f,%f %f,%f " % (x + width - rx, y + height, x + rx,
                                         y + height)
                C3 = "A %f,%f 0 0 1 %f,%f" % (rx, ry, x, y + height - ry)
                L4 = "M %f,%f %f,%f " % (x, y + height - ry, x, y + ry)
                C4 = "A %f,%f 0 0 1 %f,%f" % (rx, ry, x + rx, y)
                d = L1 + C1 + L2 + C2 + L3 + C3 + L4 + C4
            else:
                d = "M %f,%f %f,%f %f,%f %f,%f Z" % (
                    x, y, x + width, y, x + width, y + height, x, y + height)
            p = cubicsuperpath.parsePath(d)

        elif node.tag == inkex.addNS('circle', 'svg'):
            cx = float(node.get('cx'))
            cy = float(node.get('cy'))
            r = float(node.get('r'))
            d = "M %f,%f A   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f Z" % (
                cx + r, cy, r, r, cx, cy + r, r, r, cx - r, cy, r, r, cx,
                cy - r, r, r, cx + r, cy)
            p = cubicsuperpath.parsePath(d)

        elif node.tag == inkex.addNS('ellipse', 'svg'):
            cx = float(node.get('cx'))
            cy = float(node.get('cy'))
            rx = float(node.get('rx'))
            ry = float(node.get('ry'))
            d = "M %f,%f A   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f   %f,%f 0 0 1 %f,%f Z" % (
                cx + rx, cy, rx, ry, cx, cy + ry, rx, ry, cx - rx, cy, rx, ry,
                cx, cy - ry, rx, ry, cx + rx, cy)
            p = cubicsuperpath.parsePath(d)

        elif (node.tag == inkex.addNS('polygon',
                                      'svg')) or (node.tag == inkex.addNS(
                                          'polyline', 'svg')):
            points = node.get('points')
            if not points:
                return
            points = points.strip().split(" ")
            points = map(lambda x: x.split(","), points)
            d = "M "
            for point in points:
                x = float(point[0])
                y = float(point[1])
                d = d + "%f,%f " % (x, y)

            #Close the loop if it is a ploygon
            if node.tag == inkex.addNS('polygon', 'svg'):
                d = d + "Z"
            p = cubicsuperpath.parsePath(d)

        elif node.tag == inkex.addNS('line', 'svg'):
            x1 = float(node.get('x1'))
            y1 = float(node.get('y1'))
            x2 = float(node.get('x2'))
            y2 = float(node.get('y2'))
            d = "M "
            d = "M %f,%f %f,%f" % (x1, y1, x2, y2)
            p = cubicsuperpath.parsePath(d)

        else:
            return

        trans = node.get('transform')
        if trans:
            mat = simpletransform.composeTransform(
                mat, simpletransform.parseTransform(trans))
        simpletransform.applyTransformToPath(mat, p)

        ###################################################
        ## Break Curves down into small lines
        ###################################################
        f = self.flatness
        is_flat = 0
        while is_flat < 1:
            try:
                cspsubdiv.cspsubdiv(p, f)
                is_flat = 1
            except IndexError:
                break
            except:
                f += 0.1
                if f > 2:
                    break
                    #something has gone very wrong.
        ###################################################
        for sub in p:
            for i in range(len(sub) - 1):
                x1 = sub[i][1][0]
                y1 = sub[i][1][1]
                x2 = sub[i + 1][1][0]
                y2 = sub[i + 1][1][1]
                self.lines.append([x1, y1, x2, y2, rgb, path_id])
コード例 #50
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_rgbcolorpercent2(self):
     "Parse 'rgb(100%,100%,100%)'"
     col = parseColor("rgb(50%,0%,1%)")
     self.failUnlessEqual((127, 0, 2), col)
コード例 #51
0
    def effect(self):
        self.options.processmode = self.options.processmode.replace('"', '')

        start_time = time.time()
        ink_args = []

        if (self.options.spoolpath):
            if not os.path.isdir(self.options.spoolpath):
                inkex.errormsg(
                    u"Le chemin spécifié (%s) pour le répértoire de spool où seront exportés les fichier tsf est incorrect."
                    % self.options.spoolpath)
                return

        # unlock all object to be able do to what we want on it
        ink_args.append("--verb=LayerUnlockAll")
        ink_args.append("--verb=UnlockAllInAllLayers")

        # remove all objects not in selection
        if (self.onlyselected()):
            for k in self.selected:
                ink_args.append('--select=%s' % k)

            ink_args.append("--verb=EditInvertInAllLayers")
            ink_args.append("--verb=EditDelete")
            ink_args.append("--verb=FitCanvasToDrawing")

        # unlink clones
        for node in self.document.getroot().iterdescendants(
                "{http://www.w3.org/2000/svg}use"):
            ink_args.append('--select=%s' % node.get("id"))
            ink_args.append("--verb=EditUnlinkClone")

        # ungroup groups
        for node in self.document.getroot().iterdescendants(
                "{http://www.w3.org/2000/svg}g"):
            ink_args.append('--select=%s' % node.get("id"))
            ink_args.append("--verb=SelectionUnGroup")

        # convert texts to paths
        for node in self.document.getroot().iterdescendants(
                "{http://www.w3.org/2000/svg}text"):
            ink_args.append('--select=%s' % node.get("id"))
            ink_args.append("--verb=ObjectToPath")

        # ultimate un-group => remove groups generated when converting text to paths
        ink_args.append("--verb=EditSelectAll")
        ink_args.append("--verb=SelectionUnGroup")

        # ultimate object to path, convert last vector objects to paths
        ink_args.append("--verb=EditSelectAll")
        ink_args.append("--verb=ObjectToPath")

        with self.inkscaped(ink_args, needX=True) as tmp:
            # get document size to test if path are in visble zone
            print_("get document size to test if path are in visble zone %s" %
                   tmp)
            doc_width, doc_height = self.unittouu(
                self.document.getroot().get('width')), self.unittouu(
                    self.document.getroot().get('height'))
            output_file = None

            # start generating tsf
            print_("start generating tsf")
            filepath = None
            if self.options.spoolpath:
                jobanme, filepath = self.job_filepath()
                output_file = open(filepath, "w")
                self.initialize_tsf(self.options,
                                    doc_width,
                                    doc_height,
                                    jobname=jobanme,
                                    output=output_file)
            else:
                self.initialize_tsf(self.options, doc_width, doc_height)

            self.write_tsf_header()

            # get paths to cut from file, store them by color
            print_("get paths to cut from file, store them by color")
            paths_by_color = {}
            for path in self.document.getroot().iterdescendants(
                    "{http://www.w3.org/2000/svg}path"):
                path_style = simplestyle.parseStyle(path.get('style', ''))
                path_color = path_style.get('stroke', None)
                if path_color in TROTEC_COLORS:
                    try:
                        xmin, xmax, ymin, ymax = simpletransform.computeBBox(
                            [path])
                        if self.onlyselected() or all([
                                xmin >= 0, ymin >= 0, xmax <= doc_width,
                                ymax <= doc_height
                        ]):
                            path_style['stroke-opacity'] = '0'
                            path.set('style',
                                     simplestyle.formatStyle(path_style))
                            paths_by_color.setdefault(path_color,
                                                      []).append(path)
                    except TypeError:
                        pass

            with tmp_file(".bmp", text=False) as tmp_bmp:
                # generate png then bmp for engraving
                print_("generate png then bmp for engraving")
                if (self.options.processmode != 'None'):
                    self.generate_bmp(tmp_bmp)
                    if (identify_command('-format', '%k', tmp_bmp).strip() !=
                            "1"):  # If more than one color in png output
                        self.write_tsf_picture(tmp_bmp)

                # adding polygones
                print_("generate png then bmp for engraving")
                with self.draw_tsf_commands() as draw_polygon:
                    for path_color in paths_by_color:
                        r, g, b = simplestyle.parseColor(path_color)
                        for points in self.paths_to_unit_segments(
                                paths_by_color[path_color]):
                            draw_polygon(r, g, b, points)

                end_time = time.time()

            if output_file:
                try:
                    output_file.close()
                except OSError:
                    pass
            else:
                inkex.errormsg(
                    u"\n Cliquer sur valider pour terminer l'enregistrement du fichier."
                )

            # Display preview
            if self.options.preview == 'true':
                if (filepath):
                    print_("filepath : %s" % filepath)
                    try:
                        TsfFilePreviewer(filepath,
                                         export_time=round(
                                             end_time - start_time,
                                             1)).show_preview()
                    except Exception as e:
                        inkex.errormsg(
                            u"Votre fichier est prêt à être decoupé.")
                        # raise(e)
                else:
                    pass
            else:
                inkex.errormsg(u"Votre fichier est prêt à être decoupé.")
コード例 #52
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_rgbcolorpercentdecimal(self):
     "Parse 'rgb(66.667%,0%,6.667%)'"
     col = parseColor("rgb(66.667%,0%,6.667%)")
     self.failUnlessEqual((170, 0, 17), col)
コード例 #53
0
 def test_rgbcolorpercentdecimal(self):
     "Parse 'rgb(66.667%,0%,6.667%)'"
     col = parseColor('rgb(66.667%,0%,6.667%)')
     self.failUnlessEqual((170, 0, 17), col)
コード例 #54
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_currentColor(self):
     "Parse 'currentColor'"
     col = parseColor("currentColor")
     self.failUnlessEqual(("currentColor"), col)
コード例 #55
0
    def effect(self):
        self.options.processmode = self.options.processmode.replace('"', '')

        start_time = time.time()
        ink_args = []

        if(self.options.spoolpath):
            if not os.path.isdir(self.options.spoolpath):
                inkex.errormsg(u"Le chemin spécifié (%s) pour le répértoire de spool où seront exportés les fichier tsf est incorrect." % self.options.spoolpath)
                return

        # unlock all object to be able do to what we want on it
        ink_args.append("--verb=LayerUnlockAll")
        ink_args.append("--verb=UnlockAllInAllLayers")

        # remove all objects not in selection
        if(self.onlyselected()):
            for k in self.selected:
                ink_args.append('--select=%s' % k)

            ink_args.append("--verb=EditInvertInAllLayers")
            ink_args.append("--verb=EditDelete")
            ink_args.append("--verb=FitCanvasToDrawing")

        # unlink clones
        for node in self.document.getroot().iterdescendants("{http://www.w3.org/2000/svg}use"):
            ink_args.append('--select=%s' % node.get("id"))
            ink_args.append("--verb=EditUnlinkClone")

        # ungroup groups
        for node in self.document.getroot().iterdescendants("{http://www.w3.org/2000/svg}g"):
            ink_args.append('--select=%s' % node.get("id"))
            ink_args.append("--verb=SelectionUnGroup")

        # convert texts to paths
        for node in self.document.getroot().iterdescendants("{http://www.w3.org/2000/svg}text"):
            ink_args.append('--select=%s' % node.get("id"))
            ink_args.append("--verb=ObjectToPath")

        # ultimate un-group => remove groups generated when converting text to paths
        ink_args.append("--verb=EditSelectAll")
        ink_args.append("--verb=SelectionUnGroup")

        # ultimate object to path, convert last vector objects to paths
        ink_args.append("--verb=EditSelectAll")
        ink_args.append("--verb=ObjectToPath")

        with self.inkscaped(ink_args, needX=True) as tmp:
            # get document size to test if path are in visble zone
            print_("get document size to test if path are in visble zone %s" % tmp)
            doc_width, doc_height = self.unittouu(self.document.getroot().get('width')), self.unittouu(self.document.getroot().get('height'))
            output_file = None

            # start generating tsf
            print_("start generating tsf")
            filepath = None
            if self.options.spoolpath:
                jobanme, filepath = self.job_filepath()
                output_file = open(filepath, "w")
                self.initialize_tsf(self.options, doc_width, doc_height, jobname=jobanme, output=output_file)
            else:
                self.initialize_tsf(self.options, doc_width, doc_height)

            self.write_tsf_header()

            # get paths to cut from file, store them by color
            print_("get paths to cut from file, store them by color")
            paths_by_color = {}
            for path in self.document.getroot().iterdescendants("{http://www.w3.org/2000/svg}path"):
                path_style = simplestyle.parseStyle(path.get('style', ''))
                path_color = path_style.get('stroke', None)
                if path_color in TROTEC_COLORS:
                    try:
                        xmin, xmax, ymin, ymax = simpletransform.computeBBox([path])
                        if self.onlyselected() or all([xmin >= 0, ymin >= 0, xmax <= doc_width, ymax <= doc_height]):
                            path_style['stroke-opacity'] = '0'
                            path.set('style', simplestyle.formatStyle(path_style))
                            paths_by_color.setdefault(path_color, []).append(path)
                    except TypeError:
                        pass

            with tmp_file(".bmp", text=False) as tmp_bmp:
                try:
                    # generate png then bmp for engraving
                    print_("generate png then bmp for engraving")
                    if(self.options.processmode != 'None'):
                        self.generate_bmp(tmp_bmp)
                        if(identify_command('-format', '%k', tmp_bmp).strip() != "1"):  # If more than one color in png output
                            self.write_tsf_picture(tmp_bmp)
                except ImageMagickError:
                    inkex.errormsg(u"⚠️ Impossible de générer le fichier de gravure. \n\nImageMagick est il correctement installé ?\n")

                # adding polygones
                print_("generate png then bmp for engraving")
                with self.draw_tsf_commands() as draw_polygon:
                    for path_color in paths_by_color:
                        r, g, b = simplestyle.parseColor(path_color)
                        for points in self.paths_to_unit_segments(paths_by_color[path_color]):
                            draw_polygon(r, g, b, points)

                end_time = time.time()

            if output_file:
                try:
                    output_file.close()
                except OSError:
                    pass
            else:
                inkex.errormsg(u"\n Cliquer sur valider pour terminer l'enregistrement du fichier.")

            # Display preview
            if self.options.preview == 'true':
                if(filepath):
                    print_("filepath : %s" % filepath)
                    try:
                        TsfFilePreviewer(filepath, export_time=round(end_time - start_time, 1)).show_preview()
                    except Exception as e:
                        inkex.errormsg(u"Votre fichier est prêt à être decoupé.")
                        # raise(e)
                else:
                    pass
            else:
                inkex.errormsg(u"Votre fichier est prêt à être decoupé.")
コード例 #56
0
ファイル: dxf_outlines.py プロジェクト: AakashDabas/inkscape
 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.color = 7                                  # default is black
     if hsl[2]:
         self.color = 1 + (int(6*hsl[0] + 0.5) % 6)  # use 6 hues
     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', 0))
         y = float(node.get('y', 0))
         width = float(node.get('width'))
         height = float(node.get('height'))
         d = "m %s,%s %s,%s %s,%s %s,%s z" % (x, y, width, 0, 0, height, -width, 0)
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('line','svg'):
         x1 = float(node.get('x1', 0))
         x2 = float(node.get('x2', 0))
         y1 = float(node.get('y1', 0))
         y2 = float(node.get('y2', 0))
         d = "M %s,%s L %s,%s" % (x1, y1, x2, y2)
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('circle','svg'):
         cx = float(node.get('cx', 0))
         cy = float(node.get('cy', 0))
         r = float(node.get('r'))
         d = "m %s,%s a %s,%s 0 0 1 %s,%s %s,%s 0 0 1 %s,%s z" % (cx + r, cy, r, r, -2*r, 0, r, r, 2*r, 0)
         p = cubicsuperpath.parsePath(d)
     elif node.tag == inkex.addNS('ellipse','svg'):
         cx = float(node.get('cx', 0))
         cy = float(node.get('cy', 0))
         rx = float(node.get('rx'))
         ry = float(node.get('ry'))
         d = "m %s,%s a %s,%s 0 0 1 %s,%s %s,%s 0 0 1 %s,%s z" % (cx + rx, cy, rx, ry, -2*rx, 0, rx, ry, 2*rx, 0)
         p = cubicsuperpath.parsePath(d)
     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]])
コード例 #57
0
ファイル: simplestyle.test.py プロジェクト: vabz7867/inkscape
 def test_namedcolor(self):
     "Parse 'red'"
     col = parseColor("red")
     self.failUnlessEqual((255, 0, 0), col)
コード例 #58
0
ファイル: wcb_color.py プロジェクト: brucetsao/wcb-ink
	def colmod(self,r,g,b):
		#Snap to nearest color
		
		rgb = simplestyle.parseColor(self.paletteRGB[self.closestColor(r,g,b)])
		return '%02x%02x%02x' % (rgb[0], rgb[1], rgb[2])