def get_color_steps(self, total): """Get the color value, returning the start color and a single increment step""" start_value = inkex.Color(self.options.start_val) end_value = inkex.Color(self.options.end_val) color_inc = [ (end_value[v] - start_value[v]) / float(total - 1) for v in range(3)] return start_value, color_inc
def process_shape(self, node, mat): """Process shape""" 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.style if style: if 'stroke' in style: if style['stroke'] and style['stroke'] != 'none' and style[ 'stroke'][0:3] != 'url': rgb = inkex.Color(style['stroke']).to_rgb() if 'stroke-width' in style: stroke = self.svg.unittouu( style['stroke-width']) / self.svg.unittouu('1px') stroke = int(stroke * self.scale) if 'fill' in style: if style['fill'] and style['fill'] != 'none' and style['fill'][ 0:3] != 'url': fill = inkex.Color(style['fill']).to_rgb() fillcolor = fill[0] + 256 * fill[1] + 256 * 256 * fill[2] color = rgb[0] + 256 * rgb[1] + 256 * 256 * rgb[2] if isinstance(node, PathElement): p = node.path.to_superpath() if not p: return elif isinstance(node, Rectangle): 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 mat += node.transform p = Path(p).transform(Transform(mat)).to_arrays() 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(ctypes.addressof(brush)) mygdi.SelectObject(self.hDC, hBrush) mygdi.BeginPath(self.hDC) self.emit_path(p) mygdi.EndPath(self.hDC) mygdi.FillPath(self.hDC) return
def representC(value): # returns CMS color if available if (re.search("icc-color", value.group())): return str( inkex.Color( (float(1.00 - float(re.split(r'[,\)\s]+', value.group())[2])), float(1.00), float(1.00)))) else: red = float(inkex.Color(str(value.group())).to_rgb()[0] / 255.00) green = float(inkex.Color(str(value.group())).to_rgb()[1] / 255.00) blue = float(inkex.Color(str(value.group())).to_rgb()[2] / 255.00) return str( inkex.Color((float(1.00 - calculateCMYK(red, green, blue)[0]), float(1.00), float(1.00))))
def test_colors(self): """Run all color tests""" for x, (inp, outp) in enumerate(self._test_list(self.color_tests)): outp = inkex.Color(outp) got = self.effect._modify_color('fill', inkex.Color(inp)) self.assertTrue(isinstance(got, inkex.Color),\ "Bad output type: {}".format(type(got).__name__)) outp, got = str(outp), str(got.to(outp.space)) self.assertEqual(outp, got,\ "Color mismatch, test:{} {} != {}".format(x, outp, got)) for x, (inp, outp) in enumerate(self._test_list(self.opacity_tests)): got = self.effect.modify_opacity('opacity', inp) self.assertTrue(isinstance(got, float)) self.assertAlmostEqual(got, outp, delta=0.1)
def add_arguments(self, pars): # Parse the options. pars.add_argument('--tab', default='object') pars.add_argument('--clip', type=inkex.Boolean, default=False) pars.add_argument('--corner_radius', type=int, default=0) pars.add_argument('--fill_color', type=inkex.Color, default=inkex.Color(0)) pars.add_argument('--group', type=inkex.Boolean, default=False) pars.add_argument('--position', default='outside') pars.add_argument('--stroke_color', type=inkex.Color, default=inkex.Color(0)) pars.add_argument('--width', type=float, default=2.0)
def change_colors(origin, color_type): for i in range(len(str(origin).split(color_type + ':'))): if str(str(origin).split(color_type + ':')[i].split(';') [0]) in inkex.colors.SVG_COLOR.keys(): color_numbers = str( inkex.Color( inkex.Color( str( str(origin).split(color_type + ':')[i].split( ';')[0])).to_rgb())) origin = str(origin).replace( ':' + str(str(origin).split(color_type + ':')[i].split(';')[0]) + ';', ':' + color_numbers + ';') return origin
def draw_coluor_bars(self, cx, cy, rotate, name, parent, bbox): group = parent.add(inkex.Group(id=name)) group.transform = inkex.Transform(translate=(cx, cy)) * inkex.Transform(rotate=rotate) loc = 0 if bbox: loc = min(self.mark_size / 3, max(bbox.width, bbox.height) / 45) for bar in [{'c': '*', 'stroke': '#000', 'x': 0, 'y': -(loc + 1)}, {'c': 'r', 'stroke': '#0FF', 'x': 0, 'y': 0}, {'c': 'g', 'stroke': '#F0F', 'x': (loc * 11) + 1, 'y': -(loc + 1)}, {'c': 'b', 'stroke': '#FF0', 'x': (loc * 11) + 1, 'y': 0} ]: i = 0 while i <= 1: color = inkex.Color('white') if bar['c'] == 'r' or bar['c'] == '*': color.red = 255 * i if bar['c'] == 'g' or bar['c'] == '*': color.green = 255 * i if bar['c'] == 'b' or bar['c'] == '*': color.blue = 255 * i r_att = {'fill': str(color), 'stroke': bar['stroke'], 'stroke-width': loc/8, 'x': str((loc * i * 10) + bar['x']), 'y': str(bar['y']), 'width': loc, 'height': loc} rect = Rectangle() for att, value in r_att.items(): rect.set(att, value) group.add(rect) i += 0.1
def process_shape(self, node, mat): rgb = (0, 0, 0) style = node.get('style') if style: style = dict(inkex.Style.parse_str(style)) if 'stroke' in style: if style['stroke'] and style['stroke'] != 'none' and style[ 'stroke'][0:3] != 'url': rgb = inkex.Color(style['stroke']).to_rgb() hsl = colors.rgb_to_hsl(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 not isinstance(node, (PathElement, Rectangle, Line, Circle, Ellipse)): return # Transforming /after/ superpath is more reliable than before # because of some issues with arcs in transformations for sub in node.path.to_superpath().transform( Transform(mat) * node.transform): 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: self.LWPOLY_line([s[1], e[1]]) else: self.dxf_line([s[1], e[1]]) elif self.options.ROBO: self.ROBO_spline([s[1], s[2], e[0], e[1]]) else: self.dxf_spline([s[1], s[2], e[0], e[1]])
def trocar_cores(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 = str( inkex.Color( inkex.Color( str( str(origin).split(tipo_cor + ':') [i].split(';')[0])).to_rgb())) origin = str(origin).replace( ':' + str( str(origin).split(tipo_cor + ':')[i].split(';')[0]) + ';', ':' + numeros_da_cor + ';') return origin
def get_formatted_color(self, color): rgb = inkex.Color(color).to_rgb() if self.options.sort == 'hsl': key = inkex.Color(color).to_hsl() key = "{:03d}{:03d}{:03d}".format(*key) else: key = "{:03d}{:03d}{:03d}".format(*rgb) rgb = "{:3d} {:3d} {:3d}".format(*rgb) color = str(color).upper() name = str(inkex.Color(color).to_named()).upper() if name != color: name = "%s (%s)" % (name.capitalize(), color) return "%s %s %s" % (key, rgb, name)
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([inkex.Color(stop[1]).to_rgb()[c] for stop in stops]) / len(stops) for c in range(3) ] labelColour = str(inkex.Color(avgNodeColour)) return (nodeColour, labelColour)
def getLabelColour(self, nodeColour): labelColour = "#000000" try: nodeColour = inkex.Color(nodeColour).to_rgb() if sum(nodeColour) / len(nodeColour) < 128: labelColour = "#ffffff" except ( TypeError, ZeroDivisionError # if parseColor returns "" ): pass return labelColour
def effect(self): """Check each internode to see if it's in one of the wedges for the current shade. shade is a floating point 0-1 white-black""" # size of a wedge for shade i, wedges come in pairs delta = 360. / self.options.shades / 2. for node in self.svg.selection.filter(inkex.PathElement): array = node.path.to_arrays() group = None filt = None for shade in range(0, self.options.shades): if self.options.bw and 0 < shade < self.options.shades - 1: continue start = [self.options.angle - delta * (shade + 1)] end = [self.options.angle - delta * shade] start.append(self.options.angle + delta * shade) end.append(self.options.angle + delta * (shade + 1)) level = float(shade) / float(self.options.shades - 1) last = [] result = [] for cmd, params in array: if cmd == 'Z': last = [] continue if last: if cmd == 'V': point = [last[0], params[-2:][0]] elif cmd == 'H': point = [params[-2:][0], last[1]] else: point = params[-2:] ang = degrees( atan2(point[0] - last[0], point[1] - last[1])) if (self.angle_between(start[0], end[0], ang) or \ self.angle_between(start[1], end[1], ang)): result.append(('M', last)) result.append((cmd, params)) ref = point else: ref = params[-2:] last = ref if result: if group is None: group, filt = self.get_group(node) new_node = group.add(node.copy()) new_node.path = result new_node.style = 'fill:none;stroke-opacity:1;stroke-width:10' new_node.style += filt col = 255 - int(255. * level) new_node.style['stroke'] = inkex.Color((col, col, col))
def test_evil_fails(self): """ eval shouldn't allow for evil things to happen Here we try and check if a file exists but it could just as easily overwrite or delete the file """ args = [ "-r __import__('os').path.exists('__init__.py')", self.empty_svg ] self.effect.run(args) with self.assertRaises(TypeError): self.effect.modify_color('fill', inkex.Color('black'))
def add_arguments(self, pars): #Récupération des paramêtres pars.add_argument("--rows", type=int, dest="NbLigne", default=2, help="Nombre de lignes") pars.add_argument("--cols", type=int, dest="NbColonne", default=3, help="Nombre de colonnes") pars.add_argument("--units", type=str, dest="Unitee", default="mm", help="Unitée pour la cellule") pars.add_argument("--width", type=float, dest="CelL", default=10.0, help="Largeur de la cellule") pars.add_argument("--height", type=float, dest="CelH", default=20.0, help="Hauteur de la cellule") pars.add_argument("--weight", type=float, dest="ETrait", default=0.1, help="Epaisseur des traits") pars.add_argument("--color", type=inkex.Color, dest="Couleur", default=inkex.Color(0), help="Couleur des traits") pars.add_argument("--round", type=float, dest="Arrondi", default=10.0, help="Rayon de l'arrondi") pars.add_argument("--active-tab", type=str, dest="active_tab", default="options", help="Active tab.")
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
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 = inkex.Color(style[color_attrib]).to_rgb() 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] *= float(style[opacity]) return color
def process_element(self, elem): """Recursively process elements for colors""" style = elem.fallback_style(move=False) for col in inkex.Style.color_props: try: col = inkex.Color(style.get(col)) if (elem.getparent().get('inkscape:swatch') == "solid"): self.names[col] = elem.getparent().get_id() yield col except ColorIdError: gradient = self.svg.getElementById(style.get(col)) for stop in gradient.stops: for item in self.process_element(stop): yield item except ColorError: pass # Bad color if elem.href is not None: # Capture colors of symbols or clones pointing to defs for color in self.process_element(elem.href): yield color
def formatColor3f(r, g, b): """str(inkex.Color((r, g, b)))""" return str(inkex.Color((r, g, b)))
def formatColorfa(a): """str(inkex.Color(a))""" return str(inkex.Color(a))
def parseColor(c): """inkex.Color(c).to_rgb()""" return tuple(inkex.Color(c).to_rgb())
def modify_color(self, name, color): return inkex.Color((color.blue, color.red, color.green))
def modify_color(self, name, color): # ITU-R Recommendation BT.709 (NTSC and PAL) # l = 0.2125 * r + 0.7154 * g + 0.0721 * b lum = 0.299 * color.red + 0.587 * color.green + 0.114 * color.blue grey = 255 if lum > self.options.threshold else 0 return inkex.Color((grey, grey, grey))
def test_invalid_operator(self): args = ["-r r % 100", self.empty_svg] self.effect.run(args) with self.assertRaises(KeyError): self.effect.modify_color('fill', inkex.Color('black'))
def test_bad_syntax(self): args = ["-r r + 100)", self.empty_svg] self.effect.run(args) with self.assertRaises(SyntaxError): self.effect.modify_color('fill', inkex.Color('black'))
def modify_color(self, name, color): # ITU-R Recommendation BT.709 (NTSC and PAL) # l = 0.2125 * r + 0.7154 * g + 0.0721 * b lum = 0.299 * color.red + 0.587 * color.green + 0.114 * color.blue return inkex.Color((int(round(lum)), int(round(lum)), int(round(lum))))
def modify_color(self, name, color): return inkex.Color([0, color.green, color.blue])
def add_arguments(self, pars): pars.add_argument("--tab") pars.add_argument('-f', "--from_color",\ default=inkex.Color("black"), type=inkex.Color, help="Replace color") pars.add_argument('-t', "--to_color",\ default=inkex.Color("red"), type=inkex.Color, help="By color")
def effect(self): if self.options.att == 'other': if self.options.att_other is not None: inte_att = self.options.att_other else: inkex.errormsg(_("You selected 'Other'. Please enter an attribute to interpolate.")) return inte_att_type = self.options.att_other_type where = self.options.att_other_where else: inte_att = self.options.att inte_att_type = 'float' if inte_att in ('width', 'height'): where = 'tag' elif inte_att in ('scale', 'trans-x', 'trans-y'): where = 'transform' elif inte_att == 'opacity': where = 'style' elif inte_att in ('fill', 'stroke'): inte_att_type = 'color' where = 'style' collection = self.get_elements() if not collection: inkex.errormsg(_('There is no selection to interpolate')) return False if inte_att_type == 'color': cur, inc = self.get_color_steps(len(collection)) else: cur, inc = self.get_number_steps(len(collection)) for node in collection: if inte_att_type == 'color': val = inkex.Color([int(cur[i]) for i in range(3)]) elif inte_att_type == 'float': val = cur elif inte_att_type == 'int': val = int(round(cur)) else: raise KeyError("Unknown attr type: {}".format(inte_att_type)) if where == 'style': node.style[inte_att] = str(val) elif where == 'transform': if inte_att == 'trans-x': node.transform.add_translate(val, 0) elif inte_att == 'trans-y': node.transform.add_translate(0, val) elif inte_att == 'scale': node.transform.add_scale(val) elif where == 'tag': node.set(inte_att, str(val)) else: raise KeyError("Unknown update {}".format(where)) if inte_att_type == 'color': cur = [cur[i] + inc[i] for i in range(3)] else: cur += inc return True
def add_arguments(self, pars): pars.add_argument("--setcolor", default=inkex.Color("black"), type=inkex.Color, help="Replace color")