Debian Codegraph @

src/cursors/render-cursors.py

raw symbols SCIP
1 #!/usr/bin/env python2
2 #
3 # SVGSlice
4 #
5 # Released under the GNU General Public License, version 2.
6 # Email Lee Braiden of Digital Unleashed at [email protected]
7 # with any questions, suggestions, patches, or general uncertainties
8 # regarding this software.
9 #
10
11 usageMsg = """You need to add a layer called "slices", and draw rectangles on it to represent the areas that should be saved as slices. It helps when drawing these rectangles if you make them translucent.
12
13 If you name these slices using the "id" field of Inkscape's built-in XML editor, that name will be reflected in the slice filenames.
14
15 Please remember to HIDE the slices layer before exporting, so that the rectangles themselves are not drawn in the final image slices."""
16
17 # How it works:
18 #
19 # Basically, svgslice just parses an SVG file, looking for the tags that define
20 # the slices should be, and saves them in a list of rectangles. Next, it generates
21 # an XHTML file, passing that out stdout to Inkscape. This will be saved by inkscape
22 # under the name chosen in the save dialog. Finally, it calls
23 # inkscape again to render each rectangle as a slice.
24 #
25 # Currently, nothing fancy is done to layout the XHTML file in a similar way to the
26 # original document, so the generated pages is essentially just a quick way to see
27 # all of the slices in once place, and perhaps a starting point for more layout work.
28 #
29
30 from optparse import OptionParser
31
32 optParser = OptionParser()
33 optParser.add_option('-d','--debug',action='store_true',dest='debug',help='Enable extra debugging info.')
34 optParser.add_option('-t','--test',action='store_true',dest='testing',help='Test mode: leave temporary files for examination.')
35 optParser.add_option('-p','--sliceprefix',action='store',dest='sliceprefix',help='Specifies the prefix to use for individual slice filenames.')
36 optParser.add_option('-r','--remove-shadows',action='store_true',dest='remove_shadows',help='Remove shadows the cursors have.')
37 optParser.add_option('-o','--hotspots',action='store_true',dest='hotspots',help='Produce hotspot images and hotspot datafiles.')
38 optParser.add_option('-s','--scales',action='store_true',dest='scales',help='Produce 125% (Large) and 150% (Extra Large) scaled versions of each image as well.')
39 optParser.add_option('-m','--min-canvas-size',action='store',type='int',dest='min_canvas_size',default=-1, help='Cursor canvas must be at least this big (defaults to -1).')
40 optParser.add_option('-f','--fps',action='store',type='int',dest='fps',default=60,help='Assume that all animated cursors have this FPS (defaults to 60).')
41 optParser.add_option('-a','--anicursorgen',action='store_true',dest='anicur',default=False,help='Assume that anicursorgen will be used to assemble cursors (xcursorgen is assumed by default).')
42 optParser.add_option('-c','--corner-align',action='store_true',dest='align_corner',default=False,help='Align cursors to the top-left corner (by default they are centered).')
43 optParser.add_option('-i','--invert',action='store_true',dest='invert',default=False,help='Invert colors (disabled by default).')
44 optParser.add_option('-n','--number-of-renderers',action='store',type='int',dest='number_of_renderers',default=1, help='Number of renderer instances run in parallel. Defaults to 1. Set to 0 for autodetection.')
45
46 from xml.sax import saxutils, make_parser, SAXParseException, handler, xmlreader
47 from xml.sax.handler import feature_namespaces
48 import os, sys, tempfile, shutil, subprocess
49 import re
50 from threading import Thread
51 from PIL import Image
52 import multiprocessing
53 import io
54
55 svgFilename = None
56 hotsvgFilename = None
57 sizes = [24,32,48]
58 scale_pairs = [(1.25, 's1'), (1.50, 's2')]
59 mode_shadows = ['shadows']
60 mode_hotspots = ['hotspots']
61 mode_slices = ['slices']
62 mode_invert = ['invert']
63
64 def natural_sort(l):
65 convert = lambda text: int(text) if text.isdigit() else text.lower()
66 alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
67 return sorted(l, key = alphanum_key)
68
69 def dbg(msg):
70 if options.debug:
71 sys.stderr.write(msg)
72
73 def cleanup():
74 global inkscape_instances
75 for inkscape, inkscape_stderr, inkscape_stderr_thread in inkscape_instances:
76 inkscape.communicate ('quit\n')
77 del inkscape
78 del inkscape_stderr_thread
79 del inkscape_stderr
80 del inkscape_instances
81 if svgFilename != None and os.path.exists(svgFilename):
82 os.unlink(svgFilename)
83 if hotsvgFilename != None and os.path.exists(hotsvgFilename):
84 os.unlink(hotsvgFilename)
85
86 def fatalError(msg):
87 sys.stderr.write(msg)
88 cleanup()
89 sys.exit(20)
90
91 def stderr_reader(inkscape, inkscape_stderr):
92 while True:
93 line = inkscape_stderr.readline()
94 if line and len (line.rstrip ('\n').rstrip ('\r')) > 0:
95 fatalError('ABORTING: Inkscape failed to render a slice: {}'.format (line))
96 elif line:
97 print "STDERR> {}".format (line)
98 else:
99 raise UnexpectedEndOfStream
100
101 def find_hotspot (hotfile):
102 img = Image.open(hotfile)
103 pixels = img.load()
104 reddest = [-1, -1, -999999]
105 for y in range(img.size[1]):
106 for x in range(img.size[0]):
107 redness = pixels[x,y][0] - pixels[x,y][1] - pixels[x,y][2]
108 if redness > reddest[2]:
109 reddest = [x, y, redness]
110 return (reddest[0] + 1, reddest[1] + 1)
111
112 def cropalign (size, filename):
113 img = Image.open (filename)
114 content_dimensions = img.getbbox ()
115 if content_dimensions is None:
116 content_dimensions = (0, 0, img.size[0], img.size[1])
117 hcropped = content_dimensions[2] - content_dimensions[0]
118 vcropped = content_dimensions[3] - content_dimensions[1]
119 if hcropped > size or vcropped > size:
120 if hcropped > size:
121 left = (hcropped - size) / 2
122 right = (hcropped - size) - left
123 else:
124 left = 0
125 right = 0
126 if vcropped > size:
127 top = (vcropped - size) / 2
128 bottom = (vcropped - size) - top
129 else:
130 top = 0
131 bottom = 0
132 content_dimensions = (content_dimensions[0] + left, content_dimensions[1] + top, content_dimensions[2] - right, content_dimensions[3] - bottom)
133 sys.stderr.write ("WARNING: {} is too big to be cleanly cropped to {} ({}x{} at best), cropping to {}x{}!\n".format (filename, size, hcropped, vcropped, content_dimensions[2] - content_dimensions[0], content_dimensions[3] - content_dimensions[1]))
134 sys.stderr.flush ()
135 if options.testing:
136 img.save (filename + ".orig.png", "png")
137 dbg("{} content is {} {} {} {}".format (filename, content_dimensions[0], content_dimensions[1], content_dimensions[2], content_dimensions[3]))
138 cropimg = img.crop ((content_dimensions[0], content_dimensions[1], content_dimensions[2], content_dimensions[3]))
139 pixels = cropimg.load ()
140 if options.testing:
141 cropimg.save (filename + ".crop.png", "png")
142 if options.align_corner:
143 expimg = cropimg.crop ((0, 0, size, size))
144 result = (content_dimensions[0], content_dimensions[1])
145 else:
146 hslack = size - cropimg.size[0]
147 vslack = size - cropimg.size[1]
148 left = hslack / 2
149 top = vslack / 2
150 expimg = cropimg.crop ((-left, -top, size - left, size - top))
151 result = (content_dimensions[0] - left, content_dimensions[1] - top)
152 pixels = expimg.load ()
153 if options.invert:
154 negative (expimg)
155 expimg.save (filename, "png")
156 del cropimg
157 del img
158 return result
159
160 def cropalign_hotspot (new_base, size, filename):
161 if new_base is None:
162 return
163 img = Image.open (filename)
164 expimg = img.crop ((new_base[0], new_base[1], new_base[0] + size, new_base[1] + size))
165 pixels = expimg.load ()
166 expimg.save (filename, "png")
167 del img
168
169 def negative (img):
170 pixels = img.load ()
171 for y in range (0, img.size[1]):
172 for x in range (0, img.size[0]):
173 r, g, b, a = pixels[x,y]
174 pixels[x,y] = (255 - r, 255 - g, 255 - b, a)
175
176 class SVGRect:
177 """Manages a simple rectangular area, along with certain attributes such as a name"""
178 def __init__(self, x1,y1,x2,y2, name=None):
179 self.x1 = x1
180 self.y1 = y1
181 self.x2 = x2
182 self.y2 = y2
183 self.name = name
184 dbg("New SVGRect: (%s)" % name)
185
186 def renderFromSVG(self, svgFName, slicename, skipped, roundrobin, hotsvgFName):
187
188 def do_res (size, output, svgFName, skipped, roundrobin):
189 global inkscape_instances
190 if os.path.exists (output):
191 skipped[output] = True
192 return
193 command = '-w {size} -h {size} --export-id="{export_id}" --export-png="{export_png}" {svg}\n'.format (size=size, export_id=self.name, export_png=output, svg=svgFName)
194 dbg("Command: {}".format (command))
195 inkscape_instances[roundrobin[0]][0].stdin.write (command)
196
197 pngsliceFName = slicename + '.png'
198 hotsliceFName = slicename + '.hotspot.png'
199
200 dbg('Saving slice as: "%s"' % pngsliceFName)
201 for i, size in enumerate (sizes):
202 subdir = 'bitmaps/{}x{}'.format (size, size)
203 if not os.path.exists (subdir):
204 os.makedirs (subdir)
205 relslice = '{}/{}'.format (subdir, pngsliceFName)
206 do_res (size, relslice, svgFName, skipped, roundrobin)
207 if options.hotspots:
208 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
209 do_res (size, hotrelslice, hotsvgFName, skipped, roundrobin)
210 for scale in scale_pairs:
211 subdir = 'bitmaps/{}x{}_{}'.format (size, size, scale[1])
212 relslice = '{}/{}'.format (subdir, pngsliceFName)
213 if not os.path.exists (subdir):
214 os.makedirs (subdir)
215 scaled_size = int (size * scale[0])
216 do_res (scaled_size, relslice, svgFName, skipped, roundrobin)
217 if options.hotspots:
218 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
219 do_res (scaled_size, hotrelslice, hotsvgFName, skipped, roundrobin)
220 # This is not inside do_res() because we want each instance to work all scales in case scales are enabled,
221 # otherwise instances that get mostly smallscale renders will finish up way before the others
222 roundrobin[0] += 1
223 if roundrobin[0] >= options.number_of_renderers:
224 roundrobin[0] = 0
225
226 def get_next_size (index, current_size):
227 if index % 2 == 0:
228 # 24->32, 48->64, 96->128, 192->256
229 return (current_size * 4) / 3
230 else:
231 # 32->48, 64->96, 128->192, 256->384
232 return (current_size * 3) / 2
233
234 def get_csize (index, current_size):
235 size = current_size
236 if len (scale_pairs) > 0:
237 size = get_next_size (index, size)
238 return max (options.min_canvas_size, size)
239
240 def postprocess_slice (slicename, skipped):
241 pngsliceFName = slicename + '.png'
242 hotsliceFName = slicename + '.hotspot.png'
243
244 for i, size in enumerate (sizes):
245 subdir = 'bitmaps/{}x{}'.format (size, size)
246 relslice = '{}/{}'.format (subdir, pngsliceFName)
247 csize = get_csize (i, size)
248 if relslice not in skipped:
249 new_base = cropalign (csize, relslice)
250 if options.hotspots:
251 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
252 cropalign_hotspot (new_base, csize, hotrelslice)
253 for scale in scale_pairs:
254 subdir = 'bitmaps/{}x{}_{}'.format (size, size, scale[1])
255 relslice = '{}/{}'.format (subdir, pngsliceFName)
256 if relslice not in skipped:
257 new_base = cropalign (csize, relslice)
258 if options.hotspots:
259 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
260 cropalign_hotspot (new_base, csize, hotrelslice)
261
262 def write_xcur(slicename):
263 pngsliceFName = slicename + '.png'
264 hotsliceFName = slicename + '.hotspot.png'
265
266 framenum = -1
267 if slicename[-5:].startswith ('_'):
268 try:
269 framenum = int (slicename[-4:])
270 slicename = slicename[:-5]
271 except:
272 pass
273
274 # This relies on the fact that frame 1 is the first frame of an animation in the rect list
275 # If that is not so, the *icongen input file will end up missing some of the lines
276 if framenum == -1 or framenum == 1:
277 mode = 'wb'
278 else:
279 mode = 'ab'
280 if framenum == -1:
281 fps_field = ''
282 else:
283 if options.anicur:
284 # For anicursorgen use jiffies
285 fps_field = ' {}'.format (int (60.0 / options.fps))
286 else:
287 # For xcursorgen use milliseconds
288 fps_field = ' {}'.format (int (1000.0 / options.fps))
289 xcur = {}
290 xcur['s0'] = open ('bitmaps/{}.in'.format (slicename), mode)
291 if len (scale_pairs) > 0:
292 xcur['s1'] = open ('bitmaps/{}.s1.in'.format (slicename), mode)
293 xcur['s2'] = open ('bitmaps/{}.s2.in'.format (slicename), mode)
294 for i, size in enumerate (sizes):
295 subdir = 'bitmaps/{}x{}'.format (size, size)
296 relslice = '{}/{}'.format (subdir, pngsliceFName)
297 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
298 hot = find_hotspot (hotrelslice)
299 csize = get_csize (i, size)
300 xcur['s0'].write ("{csize} {hotx} {hoty} {filename}{fps_field}\n".format (csize=csize, hotx=hot[0], hoty=hot[1], filename='{}x{}/{}'.format (size, size, pngsliceFName), fps_field=fps_field))
301 for scale in scale_pairs:
302 subdir = 'bitmaps/{}x{}_{}'.format (size, size, scale[1])
303 relslice = '{}/{}'.format (subdir, pngsliceFName)
304 scaled_size = int (size * scale[0])
305 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
306 hot = find_hotspot (hotrelslice)
307 xcur[scale[1]].write ("{csize} {hotx} {hoty} {filename}{fps_field}\n".format (csize=csize, hotx=hot[0], hoty=hot[1], filename='{}x{}_{}/{}'.format (size, size, scale[1], pngsliceFName), fps_field=fps_field))
308 xcur['s0'].close ()
309 if len (scale_pairs) > 0:
310 xcur['s1'].close ()
311 xcur['s2'].close ()
312
313 def sort_file(filename):
314 with open (filename, 'rb') as src:
315 contents = src.readlines ()
316 with open (filename, 'wb') as dst:
317 for line in natural_sort (contents):
318 dst.write (line)
319
320 def sort_xcur(slicename, passed):
321 pngsliceFName = slicename + '.png'
322
323 framenum = -1
324 if slicename[-5:].startswith ('_'):
325 try:
326 framenum = int (slicename[-4:])
327 slicename = slicename[:-5]
328 except:
329 pass
330 if slicename in passed:
331 return
332 passed[slicename] = True
333
334 sort_file ('bitmaps/{}.in'.format (slicename))
335 if len (scale_pairs) > 0:
336 sort_file ('bitmaps/{}.s1.in'.format (slicename))
337 sort_file ('bitmaps/{}.s2.in'.format (slicename))
338
339 def delete_hotspot(slicename):
340 hotsliceFName = slicename + '.hotspot.png'
341
342 for i, size in enumerate (sizes):
343 subdir = 'bitmaps/{}x{}'.format (size, size)
344 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
345 if os.path.exists (hotrelslice):
346 os.unlink (hotrelslice)
347 for scale in scale_pairs:
348 subdir = 'bitmaps/{}x{}_{}'.format (size, size, scale[1])
349 hotrelslice = '{}/{}'.format (subdir, hotsliceFName)
350 if os.path.exists (hotrelslice):
351 os.unlink (hotrelslice)
352
353 class SVGHandler(handler.ContentHandler):
354 """Base class for SVG parsers"""
355 def __init__(self):
356 self.pageBounds = SVGRect(0,0,0,0)
357
358 def isFloat(self, stringVal):
359 try:
360 return (float(stringVal), True)[1]
361 except (ValueError, TypeError), e:
362 return False
363
364 def parseCoordinates(self, val):
365 """Strips the units from a coordinate, and returns just the value."""
366 if val.endswith('px'):
367 val = float(val.rstrip('px'))
368 elif val.endswith('pt'):
369 val = float(val.rstrip('pt'))
370 elif val.endswith('cm'):
371 val = float(val.rstrip('cm'))
372 elif val.endswith('mm'):
373 val = float(val.rstrip('mm'))
374 elif val.endswith('in'):
375 val = float(val.rstrip('in'))
376 elif val.endswith('%'):
377 val = float(val.rstrip('%'))
378 elif self.isFloat(val):
379 val = float(val)
380 else:
381 fatalError("Coordinate value %s has unrecognised units. Only px,pt,cm,mm,and in units are currently supported." % val)
382 return val
383
384 def startElement_svg(self, name, attrs):
385 """Callback hook which handles the start of an svg image"""
386 dbg('startElement_svg called')
387 width = attrs.get('width', None)
388 height = attrs.get('height', None)
389 self.pageBounds.x2 = self.parseCoordinates(width)
390 self.pageBounds.y2 = self.parseCoordinates(height)
391
392 def endElement(self, name):
393 """General callback for the end of a tag"""
394 dbg('Ending element "%s"' % name)
395
396
397 class SVGLayerHandler(SVGHandler):
398 """Parses an SVG file, extracing slicing rectangles from a "slices" layer"""
399 def __init__(self):
400 SVGHandler.__init__(self)
401 self.svg_rects = []
402 self.layer_nests = 0
403
404 def inSlicesLayer(self):
405 return (self.layer_nests >= 1)
406
407 def add(self, rect):
408 """Adds the given rect to the list of rectangles successfully parsed"""
409 self.svg_rects.append(rect)
410
411 def startElement_layer(self, name, attrs):
412 """Callback hook for parsing layer elements
413
414 Checks to see if we're starting to parse a slices layer, and sets the appropriate flags. Otherwise, the layer will simply be ignored."""
415 dbg('found layer: name="%s" id="%s"' % (name, attrs['id']))
416 if attrs.get('inkscape:groupmode', None) == 'layer':
417 if self.inSlicesLayer() or attrs['inkscape:label'] == 'slices':
418 self.layer_nests += 1
419
420 def endElement_layer(self, name):
421 """Callback for leaving a layer in the SVG file
422
423 Just undoes any flags set previously."""
424 dbg('leaving layer: name="%s"' % name)
425 if self.inSlicesLayer():
426 self.layer_nests -= 1
427
428 def startElement_rect(self, name, attrs):
429 """Callback for parsing an SVG rectangle
430
431 Checks if we're currently in a special "slices" layer using flags set by startElement_layer(). If we are, the current rectangle is considered to be a slice, and is added to the list of parsed
432 rectangles. Otherwise, it will be ignored."""
433 if self.inSlicesLayer():
434 x1 = self.parseCoordinates(attrs['x'])
435 y1 = self.parseCoordinates(attrs['y'])
436 x2 = self.parseCoordinates(attrs['width']) + x1
437 y2 = self.parseCoordinates(attrs['height']) + y1
438 name = attrs['id']
439 rect = SVGRect(x1,y1, x2,y2, name)
440 self.add(rect)
441
442 def startElement(self, name, attrs):
443 """Generic hook for examining and/or parsing all SVG tags"""
444 dbg('Beginning element "%s"' % name)
445 if name == 'svg':
446 self.startElement_svg(name, attrs)
447 elif name == 'g':
448 # inkscape layers are groups, I guess, hence 'g'
449 self.startElement_layer(name, attrs)
450 elif name == 'rect':
451 self.startElement_rect(name, attrs)
452
453 def endElement(self, name):
454 """Generic hook called when the parser is leaving each SVG tag"""
455 dbg('Ending element "%s"' % name)
456 if name == 'g':
457 self.endElement_layer(name)
458
459 def generateXHTMLPage(self):
460 """Generates an XHTML page for the SVG rectangles previously parsed."""
461 write = sys.stdout.write
462 write('<?xml version="1.0" encoding="UTF-8"?>\n')
463 write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">\n')
464 write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n')
465 write(' <head>\n')
466 write(' <title>Sample SVGSlice Output</title>\n')
467 write(' </head>\n')
468 write(' <body>\n')
469 write(' <p>Sorry, SVGSlice\'s XHTML output is currently very basic. Hopefully, it will serve as a quick way to preview all generated slices in your browser, and perhaps as a starting point for further layout work. Feel free to write it and submit a patch to the author :)</p>\n')
470
471 write(' <p>')
472 for rect in self.svg_rects:
473 write(' <img src="%s" alt="%s (please add real alternative text for this image)" longdesc="Please add a full description of this image" />\n' % (sliceprefix + rect.name + '.png', rect.name))
474 write(' </p>')
475
476 write('<p><a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0!" height="31" width="88" /></a></p>')
477
478 write(' </body>\n')
479 write('</html>\n')
480
481 class SVGFilter (saxutils.XMLFilterBase):
482 def __init__ (self, upstream, downstream, mode, **kwargs):
483 saxutils.XMLFilterBase.__init__(self, upstream)
484 self._downstream = downstream
485 self.mode = mode
486
487 def startDocument (self):
488 self.in_throwaway_layer_stack = [False]
489
490 def startElement (self, localname, attrs):
491 def modify_style (style, old_style, new_style=None):
492 styles = style.split (';')
493 new_styles = []
494 if old_style is not None:
495 match_to = old_style + ':'
496 for s in styles:
497 if len (s) > 0 and (old_style is None or not s.startswith (match_to)):
498 new_styles.append (s)
499 if new_style is not None:
500 new_styles.append (new_style)
501 return ';'.join (new_styles)
502
503 dict = {}
504 is_throwaway_layer = False
505 is_slices = False
506 is_hotspots = False
507 is_shadows = False
508 is_layer = False
509 if localname == 'g':
510 for key, value in attrs.items ():
511 if key == 'inkscape:label':
512 if value == 'slices':
513 is_slices = True
514 elif value == 'hotspots':
515 is_hotspots = True
516 elif value == 'shadows':
517 is_shadows = True
518 elif key == 'inkscape:groupmode':
519 if value == 'layer':
520 is_layer = True
521 if mode_shadows in self.mode and is_shadows:
522 # Only remove the shadows
523 is_throwaway_layer = True
524 elif mode_hotspots in self.mode and not (is_hotspots or is_slices):
525 # Remove all layers but hotspots and slices
526 if localname == 'g':
527 is_throwaway_layer = True
528 idict = {}
529 idict.update (attrs)
530 if 'style' not in attrs.keys ():
531 idict['style'] = ''
532 for key, value in idict.items():
533 alocalname = key
534 if alocalname == 'style':
535 had_style = True
536 if alocalname == 'style' and is_slices:
537 # Make slices invisible. Do not check the mode, because there is
538 # no circumstances where we *want* to render slices
539 value = modify_style (value, 'display', 'display:none')
540 if alocalname == 'style' and is_hotspots:
541 if mode_hotspots in self.mode:
542 # Make hotspots visible in hotspots mode
543 value = modify_style (value, 'display', 'display:inline')
544 else:
545 # Make hotspots invisible otherwise
546 value = modify_style (value, 'display', 'display:none')
547 if alocalname == 'style' and mode_invert in self.mode and is_layer and is_shadows:
548 value = modify_style (value, None, 'filter:url(#InvertFilter)')
549 dict[key] = value
550
551 if self.in_throwaway_layer_stack[0] or is_throwaway_layer:
552 self.in_throwaway_layer_stack.insert(0, True)
553 else:
554 self.in_throwaway_layer_stack.insert(0, False)
555 attrs = xmlreader.AttributesImpl(dict)
556 self._downstream.startElement(localname, attrs)
557
558 def characters(self, content):
559 if self.in_throwaway_layer_stack[0]:
560 return
561 self._downstream.characters(content)
562
563 def endElement(self, localname):
564 if self.in_throwaway_layer_stack.pop(0):
565 return
566 self._downstream.endElement(localname)
567
568 def filter_svg (input, output, mode):
569 """filter_svg(input:file, output:file, mode)
570
571 Parses the SVG input from the input stream.
572 For mode == 'hotspots' it filters out all
573 layers except for hotspots and slices. Also makes hotspots
574 visible.
575 For mode == 'shadows' it filters out the shadows layer.
576 """
577
578 mode_objs = []
579 if 'hotspots' in mode:
580 mode_objs.append (mode_hotspots)
581 if 'shadows' in mode:
582 mode_objs.append (mode_shadows)
583 if 'slices' in mode:
584 mode_objs.append (mode_slices)
585 if 'invert' in mode:
586 mode_objs.append (mode_invert)
587 if len (mode_objs) == 0:
588 raise ValueError()
589
590 output_gen = saxutils.XMLGenerator(output)
591 parser = make_parser()
592 filter = SVGFilter(parser, output_gen, mode_objs)
593 filter.setFeature(handler.feature_namespaces, False)
594 filter.setErrorHandler(handler.ErrorHandler())
595 # This little I/O dance is here to ensure that SAX parser does not stash away
596 # an open file descriptor for the input file, which would prevent us from unlinking it later
597 with open (input, 'rb') as inp:
598 contents = inp.read ()
599 contents_io = io.BytesIO (contents)
600 source_object = saxutils.prepare_input_source (contents_io)
601 filter.parse(source_object)
602 del filter
603 del parser
604 del output_gen
605
606 def autodetect_threadcount ():
607 try:
608 count = multiprocessing.cpu_count()
609 except NotImplementedError:
610 count = 1
611 return count
612
613 if __name__ == '__main__':
614 # parse command line into arguments and options
615 (options, args) = optParser.parse_args()
616
617 if len(args) != 1:
618 fatalError("\nCall me with the SVG as a parameter.\n\n")
619 originalFilename = args[0]
620
621 svgFilename = originalFilename + '.svg'
622 hotsvgFilename = originalFilename + '.hotspots.svg'
623 modes = ['slices']
624 if options.remove_shadows:
625 modes.append ('shadows')
626 if options.invert:
627 modes.append ('invert')
628
629 with open (svgFilename, 'wb') as output:
630 filter_svg(originalFilename, output, modes)
631
632 if options.hotspots:
633 with open (hotsvgFilename, 'wb') as output:
634 filter_svg(originalFilename, output, ['hotspots'])
635 # setup program variables from command line (in other words, handle non-option args)
636 basename = os.path.splitext(svgFilename)[0]
637
638 if options.sliceprefix:
639 sliceprefix = options.sliceprefix
640 else:
641 sliceprefix = ''
642
643 if not options.scales:
644 del scale_pairs[:]
645
646 if options.number_of_renderers <= 0:
647 options.number_of_renderers = autodetect_threadcount ()
648
649 inkscape_instances = []
650
651 for i in range (0, options.number_of_renderers):
652 inkscape = subprocess.Popen (['inkscape', '--without-gui', '--shell'], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
653 if inkscape is None:
654 fatalError("Failed to start Inkscape shell process")
655 inkscape_stderr = inkscape.stderr
656 inkscape_stderr_thread = Thread (target = stderr_reader, args=(inkscape, inkscape_stderr))
657 inkscape_instances.append ([inkscape, inkscape_stderr, inkscape_stderr_thread])
658
659 # initialise results before actually attempting to parse the SVG file
660 svgBounds = SVGRect(0,0,0,0)
661 rectList = []
662
663 # Try to parse the svg file
664 xmlParser = make_parser()
665 xmlParser.setFeature(feature_namespaces, 0)
666
667 # setup XML Parser with an SVGLayerHandler class as a callback parser ####
668 svgLayerHandler = SVGLayerHandler()
669 xmlParser.setContentHandler(svgLayerHandler)
670 try:
671 xmlParser.parse(svgFilename)
672 except SAXParseException, e:
673 fatalError("Error parsing SVG file '%s': line %d,col %d: %s. If you're seeing this within inkscape, it probably indicates a bug that should be reported." % (svgFilename, e.getLineNumber(), e.getColumnNumber(), e.getMessage()))
674
675 # verify that the svg file actually contained some rectangles.
676 if len(svgLayerHandler.svg_rects) == 0:
677 fatalError("""No slices were found in this SVG file. Please refer to the documentation for guidance on how to use this SVGSlice. As a quick summary:
678
679 """ + usageMsg)
680 else:
681 dbg("Parsing successful.")
682
683 #svgLayerHandler.generateXHTMLPage()
684 del xmlParser
685
686 skipped = {}
687 roundrobin = [0]
688
689 # loop through each slice rectangle, and render a PNG image for it
690 svgLayerHandler.svg_rects
691 for rect in svgLayerHandler.svg_rects:
692 slicename = sliceprefix + rect.name
693 rect.renderFromSVG(svgFilename, slicename, skipped, roundrobin, hotsvgFilename)
694
695 cleanup()
696
697 for rect in svgLayerHandler.svg_rects:
698 slicename = sliceprefix + rect.name
699 postprocess_slice(slicename, skipped)
700 if options.hotspots:
701 write_xcur(slicename)
702
703 if options.hotspots:
704 passed = {}
705 for rect in svgLayerHandler.svg_rects:
706 slicename = sliceprefix + rect.name
707 sort_xcur(slicename, passed)
708 #if not option.testing:
709 # delete_hotspot(slicename)
710
711 dbg('Slicing complete.')