Code

c190fdde031918d62c33f6e55efcc6f792aed1da
[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,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 try:
59     from lxml import etree
60 except:
61     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'))
63 def debug(what):
64     sys.stderr.write(str(what) + "\n")
65     return what
67 def errormsg(msg):
68     """Intended for end-user-visible error messages.
69     
70        (Currently just writes to stderr with an appended newline, but could do
71        something better in future: e.g. could add markup to distinguish error
72        messages from status messages or debugging output.)
73       
74        Note that this should always be combined with translation:
76          import gettext
77          _ = gettext.gettext
78          ...
79          inkex.errormsg(_("This extension requires two selected paths."))
80     """
81     sys.stderr.write(str(msg) + "\n")
82     return what
84 def check_inkbool(option, opt, value):
85     if str(value).capitalize() == 'True':
86         return True
87     elif str(value).capitalize() == 'False':
88         return False
89     else:
90         raise OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
92 def addNS(tag, ns=None):
93     val = tag
94     if ns!=None and len(ns)>0 and NSS.has_key(ns) and len(tag)>0 and tag[0]!='{':
95         val = "{%s}%s" % (NSS[ns], tag)
96     return val
98 class InkOption(optparse.Option):
99     TYPES = optparse.Option.TYPES + ("inkbool",)
100     TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
101     TYPE_CHECKER["inkbool"] = check_inkbool
103 class Effect:
104     """A class for creating Inkscape SVG Effects"""
105     def __init__(self, *args, **kwargs):
106         self.id_characters = '0123456789abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
107         self.document=None
108         self.ctx=None
109         self.selected={}
110         self.doc_ids={}
111         self.options=None
112         self.args=None
113         self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
114         self.OptionParser.add_option("--id",
115                         action="append", type="string", dest="ids", default=[], 
116                         help="id attribute of object to manipulate")
117     def effect(self):
118         pass
119     def getoptions(self,args=sys.argv[1:]):
120         """Collect command line arguments"""
121         self.options, self.args = self.OptionParser.parse_args(args)
122     def parse(self,file=None):
123         """Parse document in specified file or on stdin"""
124         try:
125             try:
126                 stream = open(file,'r')
127             except:
128                 stream = open(self.args[-1],'r')
129         except:
130             stream = sys.stdin
131         self.document = etree.parse(stream)
132         stream.close()
133     def getposinlayer(self):
134         #defaults
135         self.current_layer = self.document.getroot()
136         self.view_center = (0.0,0.0)
138         layerattr = self.document.xpath('//sodipodi:namedview/@inkscape:current-layer', namespaces=NSS)
139         if layerattr:
140             layername = layerattr[0]
141             layer = self.document.xpath('//svg:g[@id="%s"]' % layername, namespaces=NSS)
142             if layer:
143                 self.current_layer = layer[0]
145         xattr = self.document.xpath('//sodipodi:namedview/@inkscape:cx', namespaces=NSS)
146         yattr = self.document.xpath('//sodipodi:namedview/@inkscape:cy', namespaces=NSS)
147         doc_height = unittouu(self.document.getroot().get('height'))
148         if xattr and yattr:
149             x = xattr[0]
150             y = yattr[0]
151             if x and y:
152                 self.view_center = (float(x), doc_height - float(y)) # FIXME: y-coordinate flip, eliminate it when it's gone in Inkscape
153     def getselected(self):
154         """Collect selected nodes"""
155         for id in self.options.ids:
156             path = '//*[@id="%s"]' % id
157             for node in self.document.xpath(path, namespaces=NSS):
158                 self.selected[id] = node
159     def getdocids(self):
160         docIdNodes = self.document.xpath('//@id', namespaces=NSS)
161         for m in docIdNodes:
162             self.doc_ids[m] = 1
163     def output(self):
164         """Serialize document into XML on stdout"""
165         self.document.write(sys.stdout)
166     def affect(self):
167         """Affect an SVG document with a callback effect"""
168         self.getoptions()
169         self.parse()
170         self.getposinlayer()
171         self.getselected()
172         self.getdocids()
173         self.effect()
174         self.output()
175         
176     def uniqueId(self, old_id, make_new_id = True):
177         new_id = old_id
178         if make_new_id:
179             while new_id in self.doc_ids:
180                 new_id = "%s%s" % (new_id,random.choice(self.id_characters))
181             self.doc_ids[new_id] = 1
182         return new_id
183     def xpathSingle(self, path):
184         try:
185             retval = self.document.xpath(path, namespaces=NSS)[0]
186         except:
187             errormsg(_("No matching node for expression: %s") % path)
188             retval = None
189         return retval
190             
192 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99