d5c1ce2136fd630ca417fd43f8e457122d95c2f2
1 #!/usr/bin/env python
2 """
3 inkex.py
4 A helper module for creating Inkscape extensions
6 Copyright (C) 2005,2007 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, re
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 u'xml' :u'http://www.w3.org/XML/1998/namespace'
34 }
36 #a dictionary of unit to user unit conversion factors
37 uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'pc':15.0}
38 def unittouu(string):
39 '''Returns userunits given a string representation of units in another system'''
40 unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))
41 param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')
43 p = param.match(string)
44 u = unit.search(string)
45 if p:
46 retval = float(p.string[p.start():p.end()])
47 else:
48 retval = 0.0
49 if u:
50 try:
51 return retval * uuconv[u.string[u.start():u.end()]]
52 except KeyError:
53 pass
54 return retval
56 try:
57 from lxml import etree
58 except:
59 sys.exit('The fantastic lxml wrapper for libxml2 is required by inkex.py and therefore this extension. Please download and install the latest version from <http://cheeseshop.python.org/pypi/lxml/>, or install it through your package manager by a command like: sudo apt-get install python-lxml')
61 def debug(what):
62 sys.stderr.write(str(what) + "\n")
63 return what
65 def check_inkbool(option, opt, value):
66 if str(value).capitalize() == 'True':
67 return True
68 elif str(value).capitalize() == 'False':
69 return False
70 else:
71 raise OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
73 def addNS(tag, ns=None):
74 val = tag
75 if ns!=None and len(ns)>0 and NSS.has_key(ns) and len(tag)>0 and tag[0]!='{':
76 val = "{%s}%s" % (NSS[ns], tag)
77 return val
79 class InkOption(optparse.Option):
80 TYPES = optparse.Option.TYPES + ("inkbool",)
81 TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
82 TYPE_CHECKER["inkbool"] = check_inkbool
84 class Effect:
85 """A class for creating Inkscape SVG Effects"""
86 def __init__(self, *args, **kwargs):
87 self.id_characters = '0123456789abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
88 self.document=None
89 self.ctx=None
90 self.selected={}
91 self.doc_ids={}
92 self.options=None
93 self.args=None
94 self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
95 self.OptionParser.add_option("--id",
96 action="append", type="string", dest="ids", default=[],
97 help="id attribute of object to manipulate")
98 def effect(self):
99 pass
100 def getoptions(self,args=sys.argv[1:]):
101 """Collect command line arguments"""
102 self.options, self.args = self.OptionParser.parse_args(args)
103 def parse(self,file=None):
104 """Parse document in specified file or on stdin"""
105 try:
106 try:
107 stream = open(file,'r')
108 except:
109 stream = open(self.args[-1],'r')
110 except:
111 stream = sys.stdin
112 self.document = etree.parse(stream)
113 stream.close()
114 def getposinlayer(self):
115 #defaults
116 self.current_layer = self.document.getroot()
117 self.view_center = (0.0,0.0)
119 layerattr = self.document.xpath('//sodipodi:namedview/@inkscape:current-layer', NSS)
120 if layerattr:
121 layername = layerattr[0]
122 layer = self.document.xpath('//g[@id="%s"]' % layername, NSS)
123 if layer:
124 self.current_layer = layer[0]
126 xattr = self.document.xpath('//sodipodi:namedview/@inkscape:cx', NSS)
127 yattr = self.document.xpath('//sodipodi:namedview/@inkscape:cy', NSS)
128 doc_height = unittouu(self.document.getroot().get('height'))
129 if xattr and yattr:
130 x = xattr[0]
131 y = yattr[0]
132 if x and y:
133 self.view_center = (float(x), doc_height - float(y)) # FIXME: y-coordinate flip, eliminate it when it's gone in Inkscape
134 def getselected(self):
135 """Collect selected nodes"""
136 for id in self.options.ids:
137 path = '//*[@id="%s"]' % id
138 for node in self.document.xpath(path, NSS):
139 self.selected[id] = node
140 def getdocids(self):
141 docIdNodes = self.document.xpath('//@id', NSS)
142 for m in docIdNodes:
143 self.doc_ids[m] = 1
144 def output(self):
145 """Serialize document into XML on stdout"""
146 self.document.write(sys.stdout)
147 def affect(self):
148 """Affect an SVG document with a callback effect"""
149 self.getoptions()
150 self.parse()
151 self.getposinlayer()
152 self.getselected()
153 self.getdocids()
154 self.effect()
155 self.output()
157 def uniqueId(self, old_id, make_new_id = True):
158 new_id = old_id
159 if make_new_id:
160 while new_id in self.doc_ids:
161 new_id = "%s%s" % (new_id,random.choice(self.id_characters))
162 self.doc_ids[new_id] = 1
163 return new_id
164 def xpathSingle(self, path):
165 try:
166 retval = self.document.xpath(path, NSS)[0]
167 except:
168 debug("No matching node for expression: %s" % path)
169 retval = None
170 return retval