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, random
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.minidom
38 import xml.dom.ext.reader.Sax2
39 import xml.xpath
40 except:
41 sys.exit('The inkex.py module requires PyXML. Please download the latest version from <http://pyxml.sourceforge.net/>.')
43 def debug(what):
44 sys.stderr.write(str(what) + "\n")
45 return what
47 def check_inkbool(option, opt, value):
48 if str(value).capitalize() == 'True':
49 return True
50 elif str(value).capitalize() == 'False':
51 return False
52 else:
53 raise OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
55 class InkOption(optparse.Option):
56 TYPES = optparse.Option.TYPES + ("inkbool",)
57 TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
58 TYPE_CHECKER["inkbool"] = check_inkbool
61 class Effect:
62 """A class for creating Inkscape SVG Effects"""
63 def __init__(self, *args, **kwargs):
64 self.id_characters = '0123456789abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
65 self.document=None
66 self.ctx=None
67 self.selected={}
68 self.doc_ids={}
69 self.options=None
70 self.args=None
71 self.use_minidom=kwargs.pop("use_minidom", False)
72 self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
73 self.OptionParser.add_option("--id",
74 action="append", type="string", dest="ids", default=[],
75 help="id attribute of object to manipulate")
76 def effect(self):
77 pass
78 def getoptions(self,args=sys.argv[1:]):
79 """Collect command line arguments"""
80 self.options, self.args = self.OptionParser.parse_args(args)
81 def parse(self,file=None):
82 """Parse document in specified file or on stdin"""
83 reader = xml.dom.ext.reader.Sax2.Reader()
84 try:
85 try:
86 stream = open(file,'r')
87 except:
88 stream = open(self.args[-1],'r')
89 except:
90 stream = sys.stdin
91 if self.use_minidom:
92 self.document = xml.dom.minidom.parse(stream)
93 else:
94 self.document = reader.fromStream(stream)
95 self.ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)
96 stream.close()
97 def getposinlayer(self):
98 ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)
99 #defaults
100 self.current_layer = self.document.documentElement
101 self.view_center = (0.0,0.0)
103 layerattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:current-layer',self.document,context=ctx)
104 if layerattr:
105 layername = layerattr[0].value
106 layer = xml.xpath.Evaluate('//g[@id="%s"]' % layername,self.document,context=ctx)
107 if layer:
108 self.current_layer = layer[0]
110 xattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cx',self.document,context=ctx)
111 yattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cy',self.document,context=ctx)
112 if xattr and yattr:
113 x = xattr[0].value
114 y = yattr[0].value
115 if x and y:
116 self.view_center = (float(x),float(y))
117 def getselected(self):
118 """Collect selected nodes"""
119 for id in self.options.ids:
120 path = '//*[@id="%s"]' % id
121 for node in xml.xpath.Evaluate(path,self.document):
122 self.selected[id] = node
123 def getdocids(self):
124 docIdNodes = xml.xpath.Evaluate('//@id',self.document,context=self.ctx)
125 for m in docIdNodes:
126 self.doc_ids[m.value] = 1
127 def output(self):
128 """Serialize document into XML on stdout"""
129 xml.dom.ext.Print(self.document)
130 def affect(self):
131 """Affect an SVG document with a callback effect"""
132 self.getoptions()
133 self.parse()
134 self.getposinlayer()
135 self.getselected()
136 self.getdocids()
137 self.effect()
138 self.output()
140 def uniqueId(self, old_id, make_new_id = True):
141 new_id = old_id
142 if make_new_id:
143 while new_id in self.doc_ids:
144 new_id = "%s%s" % (new_id,random.choice(self.id_characters))
145 self.doc_ids[new_id] = 1
146 return new_id
147 def xpathSingle(self, path):
148 try:
149 retval = xml.xpath.Evaluate(path,self.document,context=self.ctx)[0]
150 except:
151 debug("No matching node for expression: %s" % path)
152 retval = None
153 return retval