Code

e1711105751dc02bd8dd18cc7944f0066c746a76
[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
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 try:
36     import xml.dom.ext
37     import xml.dom.ext.reader.Sax2
38     import xml.xpath
39 except:
40     sys.exit('The inkex.py module requires PyXML. Please download the latest version from <http://pyxml.sourceforge.net/>.')
42 def debug(what):
43     sys.stderr.write(str(what) + "\n")
44     return what
46 def check_inkbool(option, opt, value):
47     if str(value).capitalize() == 'True':
48         return True
49     elif str(value).capitalize() == 'False':
50         return False
51     else:
52         raise OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
54 class InkOption(optparse.Option):
55     TYPES = optparse.Option.TYPES + ("inkbool",)
56     TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
57     TYPE_CHECKER["inkbool"] = check_inkbool
60 class Effect:
61     """A class for creating Inkscape SVG Effects"""
62     def __init__(self):
63         self.document=None
64         self.selected={}
65         self.options=None
66         self.args=None
67         self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
68         self.OptionParser.add_option("--id",
69                         action="append", type="string", dest="ids", default=[], 
70                         help="id attribute of object to manipulate")
71     def effect(self):
72         pass
73     def getoptions(self,args=sys.argv[1:]):
74         """Collect command line arguments"""
75         self.options, self.args = self.OptionParser.parse_args(args)
76     def parse(self,file=None):
77         """Parse document in specified file or on stdin"""
78         reader = xml.dom.ext.reader.Sax2.Reader()
79         try:
80             try:
81                 stream = open(file,'r')
82             except:
83                 stream = open(self.args[-1],'r')
84         except:
85             stream = sys.stdin
86         self.document = reader.fromStream(stream)
87         stream.close()
88     def getposinlayer(self):
89         ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)
90         #defaults
91         self.current_layer = self.document.documentElement
92         self.view_center = (0.0,0.0)
94         layerattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:current-layer',self.document,context=ctx)
95         if layerattr:
96             layername = layerattr[0].value
97             layer = xml.xpath.Evaluate('//g[@id="%s"]' % layername,self.document,context=ctx)
98             if layer:
99                 self.current_layer = layer[0]
101         xattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cx',self.document,context=ctx)
102         yattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cy',self.document,context=ctx)
103         if xattr and yattr:
104             x = xattr[0].value
105             y = yattr[0].value
106             if x and y:
107                 self.view_center = (float(x),float(y))
108     def getselected(self):
109         """Collect selected nodes"""
110         for id in self.options.ids:
111             path = '//*[@id="%s"]' % id
112             for node in xml.xpath.Evaluate(path,self.document):
113                 self.selected[id] = node
114     def output(self):
115         """Serialize document into XML on stdout"""
116         xml.dom.ext.Print(self.document)
117     def affect(self):
118         """Affect an SVG document with a callback effect"""
119         self.getoptions()
120         self.parse()
121         self.getposinlayer()
122         self.getselected()
123         self.effect()
124         self.output()