Code

41fdcd95991c47995414dfc121148370ab3b7632
[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)
93         
94         layername = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:current-layer',self.document,context=ctx)[0].value
95         layer = xml.xpath.Evaluate('//g[@id="%s"]' % layername,self.document,context=ctx)[0]
96         if layer:
97             self.current_layer = layer
98             
99         x = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cx',self.document,context=ctx)[0].value
100         y = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cy',self.document,context=ctx)[0].value
101         if x and y:
102             self.view_center = (float(x),float(y))
103     def getselected(self):
104         """Collect selected nodes"""
105         for id in self.options.ids:
106             path = '//*[@id="%s"]' % id
107             for node in xml.xpath.Evaluate(path,self.document):
108                 self.selected[id] = node
109     def output(self):
110         """Serialize document into XML on stdout"""
111         xml.dom.ext.Print(self.document)
112     def affect(self):
113         """Affect an SVG document with a callback effect"""
114         self.getoptions()
115         self.parse()
116         self.getposinlayer()
117         self.getselected()
118         self.effect()
119         self.output()