1 #!/usr/bin/env python
2 """
3 Copyright (C) 2007-2011 Rob Antonishen; rob.antonishen@gmail.com
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 THE SOFTWARE.
23 """
24 import inkex, os, csv, math
26 try:
27 from subprocess import Popen, PIPE
28 bsubprocess = True
29 except:
30 bsubprocess = False
32 class Restack(inkex.Effect):
33 def __init__(self):
34 inkex.Effect.__init__(self)
35 self.OptionParser.add_option("-d", "--direction",
36 action="store", type="string",
37 dest="direction", default="tb",
38 help="direction to restack")
39 self.OptionParser.add_option("-a", "--angle",
40 action="store", type="float",
41 dest="angle", default=0.0,
42 help="arbitrary angle")
43 self.OptionParser.add_option("-x", "--xanchor",
44 action="store", type="string",
45 dest="xanchor", default="m",
46 help="horizontal point to compare")
47 self.OptionParser.add_option("-y", "--yanchor",
48 action="store", type="string",
49 dest="yanchor", default="m",
50 help="vertical point to compare")
51 def effect(self):
52 if len( self.selected ) > 0:
53 objlist = []
54 svg = self.document.getroot()
55 parentnode = self.current_layer
56 file = self.args[ -1 ]
58 #get all bounding boxes in file by calling inkscape again with the --query-all command line option
59 #it returns a comma seperated list structured id,x,y,w,h
60 if bsubprocess:
61 p = Popen('inkscape --query-all "%s"' % (file), shell=True, stdout=PIPE, stderr=PIPE)
62 err = p.stderr
63 f = p.communicate()[0]
64 try:
65 reader=csv.CSVParser().parse_string(f) #there was a module cvs.py in earlier inkscape that behaved differently
66 except:
67 reader=csv.reader(f.split( os.linesep ))
68 err.close()
69 else:
70 _,f,err = os.popen3('inkscape --query-all "%s"' % ( file ) )
71 reader=csv.reader( f )
72 err.close()
74 #build a dictionary with id as the key
75 dimen = dict()
76 for line in reader:
77 if len(line) > 0:
78 dimen[line[0]] = map( float, line[1:])
80 if not bsubprocess: #close file if opened using os.popen3
81 f.close
83 #find the center of all selected objects **Not the average!
84 x,y,w,h = dimen[self.selected.keys()[0]]
85 minx = x
86 miny = y
87 maxx = x + w
88 maxy = y + h
90 for id, node in self.selected.iteritems():
91 # get the bounding box
92 x,y,w,h = dimen[id]
93 if x < minx:
94 minx = x
95 if (x + w) > maxx:
96 maxx = x + w
97 if y < miny:
98 miny = y
99 if (y + h) > maxy:
100 maxy = y + h
102 midx = (minx + maxx) / 2
103 midy = (miny + maxy) / 2
105 #calculate distances for each selected object
106 for id, node in self.selected.iteritems():
107 # get the bounding box
108 x,y,w,h = dimen[id]
110 # calc the comparison coords
111 if self.options.xanchor == "l":
112 cx = x
113 elif self.options.xanchor == "r":
114 cx = x + w
115 else: # middle
116 cx = x + w / 2
118 if self.options.yanchor == "t":
119 cy = y
120 elif self.options.yanchor == "b":
121 cy = y + h
122 else: # middle
123 cy = y + h / 2
125 #direction chosen
126 if self.options.direction == "tb" or (self.options.direction == "aa" and self.options.angle == 270):
127 objlist.append([cy,id])
128 elif self.options.direction == "bt" or (self.options.direction == "aa" and self.options.angle == 90):
129 objlist.append([-cy,id])
130 elif self.options.direction == "lr" or (self.options.direction == "aa" and (self.options.angle == 0 or self.options.angle == 360)):
131 objlist.append([cx,id])
132 elif self.options.direction == "rl" or (self.options.direction == "aa" and self.options.angle == 180):
133 objlist.append([-cx,id])
134 elif self.options.direction == "aa":
135 distance = math.hypot(cx,cy)*(math.cos(math.radians(-self.options.angle)-math.atan2(cy, cx)))
136 objlist.append([distance,id])
137 elif self.options.direction == "ro":
138 distance = math.hypot(midx - cx, midy - cy)
139 objlist.append([distance,id])
140 elif self.options.direction == "ri":
141 distance = -math.hypot(midx - cx, midy - cy)
142 objlist.append([distance,id])
144 objlist.sort()
145 #move them to the top of the object stack in this order.
146 for item in objlist:
147 parentnode.append( self.selected[item[1]])
149 if __name__ == '__main__':
150 e = Restack()
151 e.affect()
154 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99