Code

Added tutorial-basic.it
[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, 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.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.id_characters = '0123456789abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
64         self.document=None
65         self.ctx=None
66         self.selected={}
67         self.doc_ids={}
68         self.options=None
69         self.args=None
70         self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
71         self.OptionParser.add_option("--id",
72                         action="append", type="string", dest="ids", default=[], 
73                         help="id attribute of object to manipulate")
74     def effect(self):
75         pass
76     def getoptions(self,args=sys.argv[1:]):
77         """Collect command line arguments"""
78         self.options, self.args = self.OptionParser.parse_args(args)
79     def parse(self,file=None):
80         """Parse document in specified file or on stdin"""
81         reader = xml.dom.ext.reader.Sax2.Reader()
82         try:
83             try:
84                 stream = open(file,'r')
85             except:
86                 stream = open(self.args[-1],'r')
87         except:
88             stream = sys.stdin
89         self.document = reader.fromStream(stream)
90         self.ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)
91         stream.close()
92     def getposinlayer(self):
93         ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)
94         #defaults
95         self.current_layer = self.document.documentElement
96         self.view_center = (0.0,0.0)
98         layerattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:current-layer',self.document,context=ctx)
99         if layerattr:
100             layername = layerattr[0].value
101             layer = xml.xpath.Evaluate('//g[@id="%s"]' % layername,self.document,context=ctx)
102             if layer:
103                 self.current_layer = layer[0]
105         xattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cx',self.document,context=ctx)
106         yattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cy',self.document,context=ctx)
107         if xattr and yattr:
108             x = xattr[0].value
109             y = yattr[0].value
110             if x and y:
111                 self.view_center = (float(x),float(y))
112     def getselected(self):
113         """Collect selected nodes"""
114         for id in self.options.ids:
115             path = '//*[@id="%s"]' % id
116             for node in xml.xpath.Evaluate(path,self.document):
117                 self.selected[id] = node
118     def getdocids(self):
119         docIdNodes = xml.xpath.Evaluate('//@id',self.document,context=self.ctx)
120         for m in docIdNodes:
121             self.doc_ids[m.value] = 1
122     def output(self):
123         """Serialize document into XML on stdout"""
124         xml.dom.ext.Print(self.document)
125     def affect(self):
126         """Affect an SVG document with a callback effect"""
127         self.getoptions()
128         self.parse()
129         self.getposinlayer()
130         self.getselected()
131         self.getdocids()
132         self.effect()
133         self.output()
134         
135     def uniqueId(self, old_id, make_new_id = True):
136         new_id = old_id
137         if make_new_id:
138             while new_id in self.doc_ids:
139                 new_id = "%s%s" % (new_id,random.choice(self.id_characters))
140             self.doc_ids[new_id] = 1
141         return new_id
142     def xpathSingle(self, path):
143         try:
144             retval = xml.xpath.Evaluate(path,self.document,context=self.ctx)[0]
145         except:
146             debug("No matching node for expression: %s" % path)
147             retval = None
148         return retval
149