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
23 import gettext
24 _ = gettext.gettext
26 #a dictionary of all of the xmlns prefixes in a standard inkscape doc
27 NSS = {
28 u'sodipodi' :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
29 u'cc' :u'http://web.resource.org/cc/',
30 u'svg' :u'http://www.w3.org/2000/svg',
31 u'dc' :u'http://purl.org/dc/elements/1.1/',
32 u'rdf' :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
33 u'inkscape' :u'http://www.inkscape.org/namespaces/inkscape',
34 u'xlink' :u'http://www.w3.org/1999/xlink',
35 u'xml' :u'http://www.w3.org/XML/1998/namespace'
36 }
38 #a dictionary of unit to user unit conversion factors
39 uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'pc':15.0}
40 def unittouu(string):
41 '''Returns userunits given a string representation of units in another system'''
42 unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))
43 param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')
45 p = param.match(string)
46 u = unit.search(string)
47 if p:
48 retval = float(p.string[p.start():p.end()])
49 else:
50 retval = 0.0
51 if u:
52 try:
53 return retval * uuconv[u.string[u.start():u.end()]]
54 except KeyError:
55 pass
56 return retval
58 def uutounit(val, unit):
59 return val/uuconv[unit]
61 try:
62 from lxml import etree
63 except:
64 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'))
66 def debug(what):
67 sys.stderr.write(str(what) + "\n")
68 return what
70 def errormsg(msg):
71 """Intended for end-user-visible error messages.
73 (Currently just writes to stderr with an appended newline, but could do
74 something better in future: e.g. could add markup to distinguish error
75 messages from status messages or debugging output.)
77 Note that this should always be combined with translation:
79 import gettext
80 _ = gettext.gettext
81 ...
82 inkex.errormsg(_("This extension requires two selected paths."))
83 """
84 sys.stderr.write((msg + "\n").encode("UTF-8"))
86 def check_inkbool(option, opt, value):
87 if str(value).capitalize() == 'True':
88 return True
89 elif str(value).capitalize() == 'False':
90 return False
91 else:
92 raise OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
94 def addNS(tag, ns=None):
95 val = tag
96 if ns!=None and len(ns)>0 and NSS.has_key(ns) and len(tag)>0 and tag[0]!='{':
97 val = "{%s}%s" % (NSS[ns], tag)
98 return val
100 class InkOption(optparse.Option):
101 TYPES = optparse.Option.TYPES + ("inkbool",)
102 TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
103 TYPE_CHECKER["inkbool"] = check_inkbool
105 class Effect:
106 """A class for creating Inkscape SVG Effects"""
107 def __init__(self, *args, **kwargs):
108 self.id_characters = '0123456789abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
109 self.document=None
110 self.ctx=None
111 self.selected={}
112 self.doc_ids={}
113 self.options=None
114 self.args=None
115 self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
116 self.OptionParser.add_option("--id",
117 action="append", type="string", dest="ids", default=[],
118 help="id attribute of object to manipulate")
119 def effect(self):
120 pass
121 def getoptions(self,args=sys.argv[1:]):
122 """Collect command line arguments"""
123 self.options, self.args = self.OptionParser.parse_args(args)
124 def parse(self,file=None):
125 """Parse document in specified file or on stdin"""
126 try:
127 try:
128 stream = open(file,'r')
129 except:
130 stream = open(self.args[-1],'r')
131 except:
132 stream = sys.stdin
133 self.document = etree.parse(stream)
134 stream.close()
135 def getposinlayer(self):
136 #defaults
137 self.current_layer = self.document.getroot()
138 self.view_center = (0.0,0.0)
140 layerattr = self.document.xpath('//sodipodi:namedview/@inkscape:current-layer', namespaces=NSS)
141 if layerattr:
142 layername = layerattr[0]
143 layer = self.document.xpath('//svg:g[@id="%s"]' % layername, namespaces=NSS)
144 if layer:
145 self.current_layer = layer[0]
147 xattr = self.document.xpath('//sodipodi:namedview/@inkscape:cx', namespaces=NSS)
148 yattr = self.document.xpath('//sodipodi:namedview/@inkscape:cy', namespaces=NSS)
149 doc_height = unittouu(self.document.getroot().get('height'))
150 if xattr and yattr:
151 x = xattr[0]
152 y = yattr[0]
153 if x and y:
154 self.view_center = (float(x), doc_height - float(y)) # FIXME: y-coordinate flip, eliminate it when it's gone in Inkscape
155 def getselected(self):
156 """Collect selected nodes"""
157 for id in self.options.ids:
158 path = '//*[@id="%s"]' % id
159 for node in self.document.xpath(path, namespaces=NSS):
160 self.selected[id] = node
161 def getdocids(self):
162 docIdNodes = self.document.xpath('//@id', namespaces=NSS)
163 for m in docIdNodes:
164 self.doc_ids[m] = 1
165 def output(self):
166 """Serialize document into XML on stdout"""
167 self.document.write(sys.stdout)
168 def affect(self):
169 """Affect an SVG document with a callback effect"""
170 self.getoptions()
171 self.parse()
172 self.getposinlayer()
173 self.getselected()
174 self.getdocids()
175 self.effect()
176 self.output()
178 def uniqueId(self, old_id, make_new_id = True):
179 new_id = old_id
180 if make_new_id:
181 while new_id in self.doc_ids:
182 new_id = "%s%s" % (new_id,random.choice(self.id_characters))
183 self.doc_ids[new_id] = 1
184 return new_id
185 def xpathSingle(self, path):
186 try:
187 retval = self.document.xpath(path, namespaces=NSS)[0]
188 except:
189 errormsg(_("No matching node for expression: %s") % path)
190 retval = None
191 return retval
194 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99