Code

listing contributors on 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,2010 Aaron Spike <aaron@ekips.org> and contributors
8 Contributors:
9   AurĂ©lio A. Heckert <aurium(a)gmail.com>
10   Bulia Byak <buliabyak@users.sf.net>
11   Nicolas Dufour, nicoduf@yahoo.fr
12   Peter J. R. Moulder <pjrm@users.sourceforge.net>
14 This program is free software; you can redistribute it and/or modify
15 it under the terms of the GNU General Public License as published by
16 the Free Software Foundation; either version 2 of the License, or
17 (at your option) any later version.
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 GNU General Public License for more details.
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27 """
28 import sys, copy, optparse, random, re
29 import gettext
30 from math import *
32 gettext.install('inkscape')
33 # _ = gettext.gettext
34 # gettext.bindtextdomain('inkscape', '/usr/share/locale')
35 # gettext.textdomain('inkscape')
37 #a dictionary of all of the xmlns prefixes in a standard inkscape doc
38 NSS = {
39 u'sodipodi' :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
40 u'cc'       :u'http://creativecommons.org/ns#',
41 u'ccOLD'    :u'http://web.resource.org/cc/',
42 u'svg'      :u'http://www.w3.org/2000/svg',
43 u'dc'       :u'http://purl.org/dc/elements/1.1/',
44 u'rdf'      :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
45 u'inkscape' :u'http://www.inkscape.org/namespaces/inkscape',
46 u'xlink'    :u'http://www.w3.org/1999/xlink',
47 u'xml'      :u'http://www.w3.org/XML/1998/namespace'
48 }
50 #a dictionary of unit to user unit conversion factors
51 uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'm':3543.3070866,
52           'km':3543307.0866, 'pc':15.0, 'yd':3240 , 'ft':1080}
53 def unittouu(string):
54     '''Returns userunits given a string representation of units in another system'''
55     unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))
56     param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')
58     p = param.match(string)
59     u = unit.search(string)    
60     if p:
61         retval = float(p.string[p.start():p.end()])
62     else:
63         retval = 0.0
64     if u:
65         try:
66             return retval * uuconv[u.string[u.start():u.end()]]
67         except KeyError:
68             pass
69     return retval
71 def uutounit(val, unit):
72     return val/uuconv[unit]
74 try:
75     from lxml import etree
76 except Exception, e:
77     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\n\nTechnical details:\n%s" % (e,)))
78  
80 def debug(what):
81     sys.stderr.write(str(what) + "\n")
82     return what
84 def errormsg(msg):
85     """Intended for end-user-visible error messages.
86     
87        (Currently just writes to stderr with an appended newline, but could do
88        something better in future: e.g. could add markup to distinguish error
89        messages from status messages or debugging output.)
90       
91        Note that this should always be combined with translation:
93          import gettext
94          _ = gettext.gettext
95          ...
96          inkex.errormsg(_("This extension requires two selected paths."))
97     """
98     sys.stderr.write((unicode(msg) + "\n").encode("UTF-8"))
100 def check_inkbool(option, opt, value):
101     if str(value).capitalize() == 'True':
102         return True
103     elif str(value).capitalize() == 'False':
104         return False
105     else:
106         raise optparse.OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
108 def addNS(tag, ns=None):
109     val = tag
110     if ns!=None and len(ns)>0 and NSS.has_key(ns) and len(tag)>0 and tag[0]!='{':
111         val = "{%s}%s" % (NSS[ns], tag)
112     return val
114 class InkOption(optparse.Option):
115     TYPES = optparse.Option.TYPES + ("inkbool",)
116     TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
117     TYPE_CHECKER["inkbool"] = check_inkbool
119 class Effect:
120     """A class for creating Inkscape SVG Effects"""
122     def __init__(self, *args, **kwargs):
123         self.document=None
124         self.ctx=None
125         self.selected={}
126         self.doc_ids={}
127         self.options=None
128         self.args=None
129         self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
130         self.OptionParser.add_option("--id",
131                         action="append", type="string", dest="ids", default=[], 
132                         help="id attribute of object to manipulate")
134     def effect(self):
135         pass
137     def getoptions(self,args=sys.argv[1:]):
138         """Collect command line arguments"""
139         self.options, self.args = self.OptionParser.parse_args(args)
141     def parse(self,file=None):
142         """Parse document in specified file or on stdin"""
143         try:
144             try:
145                 stream = open(file,'r')
146             except:
147                 stream = open(self.svg_file,'r')
148         except:
149             stream = sys.stdin
150         self.document = etree.parse(stream)
151         stream.close()
153     def getposinlayer(self):
154         #defaults
155         self.current_layer = self.document.getroot()
156         self.view_center = (0.0,0.0)
158         layerattr = self.document.xpath('//sodipodi:namedview/@inkscape:current-layer', namespaces=NSS)
159         if layerattr:
160             layername = layerattr[0]
161             layer = self.document.xpath('//svg:g[@id="%s"]' % layername, namespaces=NSS)
162             if layer:
163                 self.current_layer = layer[0]
165         xattr = self.document.xpath('//sodipodi:namedview/@inkscape:cx', namespaces=NSS)
166         yattr = self.document.xpath('//sodipodi:namedview/@inkscape:cy', namespaces=NSS)
167         doc_height = unittouu(self.document.getroot().get('height'))
168         if xattr and yattr:
169             x = xattr[0]
170             y = yattr[0]
171             if x and y:
172                 self.view_center = (float(x), doc_height - float(y)) # FIXME: y-coordinate flip, eliminate it when it's gone in Inkscape
174     def getselected(self):
175         """Collect selected nodes"""
176         for i in self.options.ids:
177             path = '//*[@id="%s"]' % i
178             for node in self.document.xpath(path, namespaces=NSS):
179                 self.selected[i] = node
181     def getElementById(self, id):
182         path = '//*[@id="%s"]' % id
183         el_list = self.document.xpath(path, namespaces=NSS)
184         if el_list:
185           return el_list[0]
186         else:
187           return None
189     def getParentNode(self, node):
190         for parent in self.document.getiterator():
191             if node in parent.getchildren():
192                 return parent
193                 break
196     def getdocids(self):
197         docIdNodes = self.document.xpath('//@id', namespaces=NSS)
198         for m in docIdNodes:
199             self.doc_ids[m] = 1
201     def getNamedView(self):
202         return self.document.xpath('//sodipodi:namedview', namespaces=NSS)[0]
204     def createGuide(self, posX, posY, angle):
205         atts = {
206           'position': str(posX)+','+str(posY),
207           'orientation': str(sin(radians(angle)))+','+str(-cos(radians(angle)))
208           }
209         guide = etree.SubElement(
210                   self.getNamedView(),
211                   addNS('guide','sodipodi'), atts )
212         return guide
214     def output(self):
215         """Serialize document into XML on stdout"""
216         self.document.write(sys.stdout)
218     def affect(self, args=sys.argv[1:], output=True):
219         """Affect an SVG document with a callback effect"""
220         self.svg_file = args[-1]
221         self.getoptions(args)
222         self.parse()
223         self.getposinlayer()
224         self.getselected()
225         self.getdocids()
226         self.effect()
227         if output: self.output()
229     def uniqueId(self, old_id, make_new_id = True):
230         new_id = old_id
231         if make_new_id:
232             while new_id in self.doc_ids:
233                 new_id += random.choice('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
234             self.doc_ids[new_id] = 1
235         return new_id
237     def xpathSingle(self, path):
238         try:
239             retval = self.document.xpath(path, namespaces=NSS)[0]
240         except:
241             errormsg(_("No matching node for expression: %s") % path)
242             retval = None
243         return retval
244             
246 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99