import sys # base class for SVG objects, holding style information and handing rendering class svgstyled(object): id = 0 def __init__(self,tag): self.tag = tag self.style = {} self.attrs = {} self.content = '' self.id = "sv"+str(svgstyled.id) svgstyled.id += 1 # add a style def addStyle(self,name,value): self.style[name] = value return self # add an SVG attribute def addAttr(self,name,value): self.attrs[name] = value return self # set the XML content of the element def setContent(self,content): self.content = content return self # render all attributes to a string def getAttrs(self): s = '' for name in self.attrs: s += ' %s="%s"'%(name,str(self.attrs[name])) s += self.getStyleAttr() return s # render the style attribute def getStyleAttr(self): keys = self.style.keys() s = '' if len(keys): s = ' style="' for k in keys: s += k + ":" + str(self.style[k])+";" s += '" ' return s # render the object as an SVG string def svg(self): s = '<' + self.tag s += self.getAttrs() if self.content != '': s += '>' s += self.content s += '\n' else: s += '/>\n' return s # get a unique identifier string for this object def getId(self): return self.id # represent a section of text as an SVG object class text(svgstyled): def __init__(self,x,y,txt,hide=False,id=None): svgstyled.__init__(self,"text") self.addAttr("x",x).addAttr("y",y).setContent(txt) if id: self.addAttr("id",id) if hide: self.addStyle("display","none") # represent a circle as an SVG object class circle(svgstyled): def __init__(self,x,y,r,col): svgstyled.__init__(self,'circle') self.addAttr("cx",x).addAttr("cy",y).addAttr("r",r).addAttr("fill",col) # represent a polygon as an SVG object class polygon(svgstyled): def __init__(self,points,fill,stroke,stroke_width,tooltip_id=None): svgstyled.__init__(self,"path") s = 'M' sep = '' for (x,y) in points: s += sep sep = ' ' s += str(x)+","+str(y) s += 'Z' self.addAttr("d",s).addAttr("id",self.id).addAttr("fill","rgb(%d,%d,%d)"%fill) self.addAttr("stroke-width",stroke_width).addAttr("stroke","rgb(%d,%d,%d)"%stroke) if tooltip_id: self.addAttr("class",tooltip_id) self.addAttr("onmouseover","showToolTip(evt,'%s',true)"%tooltip_id) self.addAttr("onmouseout","showToolTip(evt,'%s',false)"%tooltip_id) class svgdoc(object): # construct a document with a given width and height, and javascript to embed def __init__(self,width,height,jscode): self.objects = [] self.width = width self.height = height self.jscode = jscode # add an object to the document (obj inherits from svgstyled) def add(self,obj): self.objects.append(obj) # render the document as SVG and return as string def render(self): # add the XML header txt = """ """%{ 'height':self.height, 'width':self.width } # add the javascript if self.jscode != '': txt += '' # add the objects for o in self.objects: txt += o.svg() txt += '' return txt