1 # -*- coding: iso-8859-1 -*- 2 """ 3 MoinMoin - SVGChart 4 5 @copyright: 2011 by Paul Boddie <paul@boddie.org.uk> 6 @license: GNU GPL (v2 or later), see COPYING.txt for details. 7 """ 8 9 from MoinMoin import wikiutil 10 from MoinMoin.action import AttachFile 11 from SVGChartSupport import get_chart, get_dimensions 12 13 try: 14 from hashlib import sha1 15 except ImportError: 16 from sha import new as sha1 17 18 Dependencies = ["pages"] 19 20 # Parser support. 21 22 class Parser: 23 24 "Format CSV-like data as an SVG chart." 25 26 extensions = [".csv"] 27 28 def __init__(self, raw, request, **kw): 29 30 """ 31 Initialise the parser with the given 'raw' data, 'request' and any 32 keyword arguments that may have been supplied. 33 """ 34 35 self.raw = raw 36 self.request = request 37 self.data = [row.split() for row in raw.split("\n")] 38 39 attrs, msg = wikiutil.parseAttributes(request, kw.get("format_args", "")) 40 41 # The attributes returned from the formatting arguments are encoded like 42 # strings. 43 44 quotes = '"' + "'" 45 self.xorigin = float((attrs.get("xorigin") or '0').strip(quotes)) 46 self.yorigin = float((attrs.get("yorigin") or '0').strip(quotes)) 47 width = (attrs.get("width") or '').strip(quotes) or None 48 height = (attrs.get("height") or '').strip(quotes) or None 49 self.width = width and int(width) 50 self.height = height and int(height) 51 52 def format(self, fmt): 53 54 "Format a chart using the given formatter 'fmt'." 55 56 request = self.request 57 page = request.page 58 _ = request.getText 59 60 data = "%s,%s,%s,%s,%s" % (self.width, self.height, self.xorigin, self.yorigin, self.raw) 61 filename = "SVGChart-%s.svg" % sha1(data).hexdigest() 62 pagename = page.page_name 63 64 if not AttachFile.exists(request, pagename, filename): 65 width, height, chart = get_chart(self.data, self.width, self.height, self.xorigin, self.yorigin, 66 styles_url="%s/%s/css/svgchart.css" % (request.cfg.url_prefix_static, request.theme.name)) 67 AttachFile.add_attachment(request, pagename, filename, chart.encode("utf-8")) 68 else: 69 width, height = get_dimensions(self.data, self.width, self.height, self.xorigin, self.yorigin) 70 71 request.write(fmt.div(1, css_class="svgchart")) 72 request.write(fmt.transclusion(1, data=AttachFile.getAttachUrl(pagename, filename, request), width=width, height=height)) 73 request.write(fmt.text(_("SVG chart of CSV data."))) 74 request.write(fmt.transclusion(0)) 75 request.write(fmt.div(0)) 76 77 # vim: tabstop=4 expandtab shiftwidth=4