Code

move user unit conversion into inkex.py
[inkscape.git] / share / extensions / inkex.py
1 #!/usr/bin/env python
2 """
3 inkex.py
4 A helper module for creating Inkscape extensions
6 Copyright (C) 2005 Aaron Spike, aaron@ekips.org
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 """
22 import sys, copy, optparse, random
24 #a dictionary of all of the xmlns prefixes in a standard inkscape doc
25 NSS = {
26 u'sodipodi'    :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
27 u'cc'        :u'http://web.resource.org/cc/',
28 u'svg'        :u'http://www.w3.org/2000/svg',
29 u'dc'        :u'http://purl.org/dc/elements/1.1/',
30 u'rdf'        :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
31 u'inkscape'    :u'http://www.inkscape.org/namespaces/inkscape',
32 u'xlink'    :u'http://www.w3.org/1999/xlink'
33 }
35 #a dictionary of unit to user unit conversion factors
36 uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'pc':15.0}
37 def unittouu(string):
38     '''Returns returns userunits given a string representation of units in another system'''
39     unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))
40     param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')
42     p = param.match(string)
43     u = unit.search(string)    
44     if p:
45         retval = float(p.string[p.start():p.end()])
46     else:
47         retval = 0.0
48     if u:
49         try:
50             return retval * uuconv[u.string[u.start():u.end()]]
51         except KeyError:
52             pass
53     return retval
55 try:
56     import xml.dom.ext
57     import xml.dom.minidom
58     import xml.dom.ext.reader.Sax2
59     import xml.xpath
60 except:
61     sys.exit('The inkex.py module requires PyXML. Please download the latest version from <http://pyxml.sourceforge.net/>.')
63 def debug(what):
64     sys.stderr.write(str(what) + "\n")
65     return what
67 def check_inkbool(option, opt, value):
68     if str(value).capitalize() == 'True':
69         return True
70     elif str(value).capitalize() == 'False':
71         return False
72     else:
73         raise OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
75 class InkOption(optparse.Option):
76     TYPES = optparse.Option.TYPES + ("inkbool",)
77     TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
78     TYPE_CHECKER["inkbool"] = check_inkbool
81 class Effect:
82     """A class for creating Inkscape SVG Effects"""
83     def __init__(self, *args, **kwargs):
84         self.id_characters = '0123456789abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
85         self.document=None
86         self.ctx=None
87         self.selected={}
88         self.doc_ids={}
89         self.options=None
90         self.args=None
91         self.use_minidom=kwargs.pop("use_minidom", False)
92         self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
93         self.OptionParser.add_option("--id",
94                         action="append", type="string", dest="ids", default=[], 
95                         help="id attribute of object to manipulate")
96     def effect(self):
97         pass
98     def getoptions(self,args=sys.argv[1:]):
99         """Collect command line arguments"""
100         self.options, self.args = self.OptionParser.parse_args(args)
101     def parse(self,file=None):
102         """Parse document in specified file or on stdin"""
103         reader = xml.dom.ext.reader.Sax2.Reader()
104         try:
105             try:
106                 stream = open(file,'r')
107             except:
108                 stream = open(self.args[-1],'r')
109         except:
110             stream = sys.stdin
111         if self.use_minidom:
112             self.document = xml.dom.minidom.parse(stream)
113         else:
114             self.document = reader.fromStream(stream)
115         self.ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)
116         stream.close()
117     def getposinlayer(self):
118         ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)
119         #defaults
120         self.current_layer = self.document.documentElement
121         self.view_center = (0.0,0.0)
123         layerattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:current-layer',self.document,context=ctx)
124         if layerattr:
125             layername = layerattr[0].value
126             layer = xml.xpath.Evaluate('//g[@id="%s"]' % layername,self.document,context=ctx)
127             if layer:
128                 self.current_layer = layer[0]
130         xattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cx',self.document,context=ctx)
131         yattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cy',self.document,context=ctx)
132         if xattr and yattr:
133             x = xattr[0].value
134             y = yattr[0].value
135             if x and y:
136                 self.view_center = (float(x),float(y))
137     def getselected(self):
138         """Collect selected nodes"""
139         for id in self.options.ids:
140             path = '//*[@id="%s"]' % id
141             for node in xml.xpath.Evaluate(path,self.document):
142                 self.selected[id] = node
143     def getdocids(self):
144         docIdNodes = xml.xpath.Evaluate('//@id',self.document,context=self.ctx)
145         for m in docIdNodes:
146             self.doc_ids[m.value] = 1
147     def output(self):
148         """Serialize document into XML on stdout"""
149         xml.dom.ext.Print(self.document)
150     def affect(self):
151         """Affect an SVG document with a callback effect"""
152         self.getoptions()
153         self.parse()
154         self.getposinlayer()
155         self.getselected()
156         self.getdocids()
157         self.effect()
158         self.output()
159         
160     def uniqueId(self, old_id, make_new_id = True):
161         new_id = old_id
162         if make_new_id:
163             while new_id in self.doc_ids:
164                 new_id = "%s%s" % (new_id,random.choice(self.id_characters))
165             self.doc_ids[new_id] = 1
166         return new_id
167     def xpathSingle(self, path):
168         try:
169             retval = xml.xpath.Evaluate(path,self.document,context=self.ctx)[0]
170         except:
171             debug("No matching node for expression: %s" % path)
172             retval = None
173         return retval
174