-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlarscwallin.inx.extractelements.py
483 lines (378 loc) · 16.8 KB
/
larscwallin.inx.extractelements.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#!/usr/bin/env python
# These two lines are only needed if you don't put the script directly into
# the installation directory
import sys
import base64
import string
import webbrowser
import threading
import os.path
import math
import re
sys.path.append('/usr/share/inkscape/extensions')
import SvgDocument
import inkex
import simpletransform
import simplepath
import simplestyle
from scour import scourString
class ExtractElements(inkex.Effect):
exportTemplate = """<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 {{element.width}} {{element.height}}" xml:space="preserve" preserveAspectRatio="xMinYMin">
<style/>
{{element.source}}
{{js}}
</svg>"""
cssTemplate = """.{{css.prefix}}{{element.label}}{{css.suffix}}:url({{element.source}});"""
sassTemplate = """${{sass.var.prefix}}{{element.label}}{{sass.var.suffix}}="{{element.source}}";"""
js = """<script>
<![CDATA[
(function(){if(0<document.location.href.indexOf("?")){var e=[],a=[],a=[],b="",c,d="",f=!1,g="fill fill-opacity fill-rule display stroke stroke-opacity stroke-width".split(" "),b=location.href;""!==document.location.hash&&(a=document.location.href.split("#"),0<a.length?(c=a[1],b=a[0]):c=!1);b=b.split("?");1<b.length&&(a=b[1].split("&"),0<a.length&&a.forEach(function(a){a=a.split("=");0<=g.indexOf(a[0])&&(f=!0,e.push(a))}),f&&(c=c?document.getElementById(c):document.getElementsByTagName("svg")[0]))&&
(e.forEach(function(a){var b;2===a.length&&(b=a[1],d+=a[0]+":"+b+";")}),""!=d&&c.setAttribute("style",d))}})();
]]>
</script>"""
def __init__(self):
"""
Constructor.
Defines the "--what" option of a script.
"""
# Call the base class constructor.
inkex.Effect.__init__(self)
self.OptionParser.add_option('-w', '--where', action = 'store',
type = 'string', dest = 'where', default = '',
help = '')
self.OptionParser.add_option('--encode', action = 'store',
type = 'inkbool', dest = 'encode', default = False,
help = 'Base64 encode the result?')
self.OptionParser.add_option('--viewresult', action = 'store',
type = 'inkbool', dest = 'viewresult', default = False,
help = 'View resulting?')
self.OptionParser.add_option('--resize', action = 'store',
type = 'inkbool', dest = 'resize', default = False,
help = 'Resize the drawing canvas to the elements?')
self.OptionParser.add_option('--reposition', action = 'store',
type = 'inkbool', dest = 'reposition', default = False,
help = 'Reposition elements to the top left corner of the drawing?')
self.OptionParser.add_option('--scour', action = 'store',
type = 'inkbool', dest = 'scour', default = False,
help = 'Clean up drawing source using Scour?')
self.OptionParser.add_option('--includejs', action = 'store',
type = 'inkbool', dest = 'includejs', default = False,
help = 'Include Javascript to support ?color=hexvalue parameter?')
def effect(self):
"""
Effect behaviour.
"""
self.where = self.options.where
self.base64Encode = self.options.encode
self.viewResult = self.options.viewresult
self.resizeDrawing = self.options.resize
self.reposition = self.options.reposition
self.scour = self.options.scour
self.renderSass = True
self.includeJS = self.options.includejs
self.CSSSource = []
self.getselected()
self.svgDoc = self.document.xpath('//svg:svg',namespaces=inkex.NSS)[0]
self.svgWidth = inkex.unittouu(self.svgDoc.get('width'))
self.svgHeight = inkex.unittouu(self.svgDoc.get('height'))
overideElementDim = False
# Temporary solution where I grab all defs, regardless of if they are actually used or not
# defs = self.document.xpath('//svg:svg/svg:defs',namespaces=inkex.NSS)[0]
layers = self.document.xpath('//svg:svg/svg:g[@style!="display:none"]',namespaces=inkex.NSS)
"""
if(len(defs) > 0):
defs = inkex.etree.tostring(defs)
else:
defs = '<defs/>'
"""
# If no elements where selected we default to exporting every visible layer in the drawing
if(self.selected.__len__() <= 0):
self.selected = layers
# As we are exporting whole layers we assume that the resulting SVG drawings has the
# same dimensions as the source document and thus overide the elements bounding box.
overideElementDim = True
else:
self.selected = self.selected.values()
if(self.selected.__len__() > 0):
selected = []
# Iterate through all selected elements
for element in self.selected:
elementLabel = str(element.get(inkex.addNS('label', 'inkscape'),''))
elementId = element.get('id')
if(elementLabel != ''):
element.set('label',elementLabel)
element.set('class',elementLabel)
else:
pass
tagName= self.getTagName(element)
if(tagName == 'path'):
# Paths can easily be moved by recalculating their d attributes
if(self.reposition or self.resizeDrawing):
pathData = self.movePath(element,0,0,'tl')
if(pathData):
element.set('d',pathData)
elif(tagName == 'g'):
# Groups however are best "transformed" into place using translate
# self.translateElement(element,0,0,False)
pass
elementBox = list(simpletransform.computeBBox([element]))
elementBox[1] = (elementBox[1]-elementBox[0])
elementBox[3] = (elementBox[3]-elementBox[2])
if(overideElementDim == False):
elementWidth = elementBox[1]
elementHeight = elementBox[3]
else:
elementWidth = self.svgWidth
elementHeight = self.svgHeight
elementSource = inkex.etree.tostring(element)
if(elementSource!=''):
# Wrap the node in an SVG doc
if(self.resizeDrawing):
tplResult = string.replace(self.exportTemplate,'{{element.width}}',str(elementWidth))
tplResult = string.replace(tplResult,'{{element.height}}',str(elementHeight))
else:
tplResult = string.replace(self.exportTemplate,'{{element.width}}',str(self.svgWidth))
tplResult = string.replace(tplResult,'{{element.height}}',str(self.svgHeight))
#tplResult = string.replace(tplResult,'{{document.defs}}',defs)
tplResult = string.replace(tplResult,'{{element.source}}',elementSource)
if(self.includeJS):
tplResult = string.replace(tplResult,'{{js}}',self.js)
else:
tplResult = string.replace(tplResult,'{{js}}','')
if(self.scour):
tplResult = self.scourDoc(tplResult)
# If the result of the operation is valid, add the SVG source to the selected array
if(tplResult):
selected.append({
'id':elementId,
'label':elementLabel,
'source':tplResult,
'box':elementBox
})
for node in selected:
# Cache these in local vars
content = node['source']
id = node['id']
label = node['label'] or node['id']
if(content!=''):
if(self.base64Encode):
if(self.renderSass):
content = ('$data-url-'+label+':"data:image/svg+xml;name='+label+';base64,'+(base64.b64encode(content))+'";')
#node['source'] = ('data:image/svg+xml;name='+label+';base64,'+(base64.b64encode(content)))
#content = self.renderSassStyle(node)
else:
pass
#content = ('data:image/svg+xml;name='+label+';base64,'+(base64.b64encode(content)))
if(self.where!=''):
# The easiest way to name rendered elements is by using their id since we can trust that this is always unique.
filename = os.path.join(self.where, (id+'-'+label+'.svg'))
success = self.saveToFile(content,filename)
if(success):
if(self.viewResult):
self.viewOutput(filename)
else:
inkex.debug('Unable to write to file "' + filename + '"')
else:
if(self.viewResult):
if(self.base64Encode):
inkex.debug(content)
inkex.debug('')
#self.viewOutput('data:image/svg+xml;base64,'+content)
else:
inkex.debug(content)
inkex.debug('')
#self.viewOutput('data:image/svg+xml,'+content)
else:
inkex.debug(content)
else:
inkex.debug('No SVG source available for element ' + id)
else:
inkex.debug('No SVG elements or layers to extract.')
def renderCSS(source):
pass
#if(source):
#self.CSSSource = (self.CSSSource + '')
def renderSassStyle(source):
if(source):
self.CSSSource = (self.CSSSource + '')
def getTagName(self,node):
type = node.get(inkex.addNS('type', 'sodipodi'))
if(type == None):
#remove namespace data {....}
tagName= node.tag
tagName= tagName.split('}')[1]
else:
tagName= str(type)
return tagName
# Move element using transform translate
def translateElement(self,node,x,y,relative = False):
# Grab transform attribute if it exists.
transform = node.get('transform','')
# Compute the nodes bounding box
box =list(simpletransform.computeBBox([node]))
pos_x = box[0]
pos_y = box[2]
# rotation center is not a breeze to calculate from the matrix, so thanks inkscape ;)
origin_x = float(node.get(inkex.addNS('transform-center-x', 'inkscape'),0))
origin_y = float(node.get(inkex.addNS('transform-center-y', 'inkscape'),0))
origin_x = origin_x + ( box[1] / 2)
origin_y = (origin_y * -1) + ( box[3] / 2)
if(transform==''):
# If there is no transform attribute on the node we add one
node.attrib['transform'] = ''
# simpletransform returns a multi dim array of matrix values
transform = simpletransform.parseTransform(transform)
transformObject = self.normalizeMatrix(transform)
inkex.debug(transformObject)
#offset_x = (transform[0][2]-pos_x)
#offset_y = (transform[1][2]-pos_y)
offset_x = (pos_x * -1)
offset_y = (pos_y * -1)
inkex.debug([offset_x,offset_y])
transform = simpletransform.parseTransform(('translate(' + str(offset_x) + ' ' + str(offset_y) + ')'),transform)
transformObject = self.normalizeMatrix(transform)
inkex.debug(transformObject)
inkex.debug(transform)
if(relative == False):
matrix = simpletransform.formatTransform(transform)
node.set('transform',matrix)
inkex.debug(matrix)
else:
simpletransform.applyTransformToNode(transform,node)
def parseStyleAttribute(self,str):
#inkex.debug(self.debug_tab + 'Got style ' + str)
rules = str.split(';')
parsed_set = {}
result = ''
for rule in rules:
parts = rule.split(':')
if(len(parts) > 1):
key = self.camelConvert(parts[0])
val = self.camelConvert(parts[1])
if(key== 'filter'):
parsed_set['filter'] = self.parseFilter(val)
elif(key == 'fill' and val.find('url(#') > -1):
parsed_set['fillGradient'] = self.parseGradient(val)
elif(key == 'stroke' and val.find('url(#') > -1):
parsed_set['strokeGradient'] = self.parseGradient(val)
else:
parsed_set[key] = val
return parsed_set
def expandMatrix(self,normalizedMatrix):
pass
def normalizeMatrix(self,matrix):
degree = 180 / math.pi
radian = math.pi / 180
a = matrix[0][0]
b = matrix[1][0]
c = matrix[0][1]
d = matrix[1][1]
tx = matrix[0][2]
ty = matrix[1][2]
scaleX = math.sqrt((a * a) + (c * c))
scaleY = math.sqrt((b * b) + (d * d))
sign = math.atan(-c / a)
rad = math.acos(a / scaleX)
deg = rad * degree
reflectX = (a < 0)
reflectY = (d < 0)
if (deg > 90 and sign > 0):
rotation = (360 - deg) * radian
elif (deg < 90 and sign < 0):
rotation = (360 - deg) * radian
else:
rotation = rad
rotationInDegree = rotation * degree
# If we have a reflected matrix we subtract 180 degrees
if(reflectX or reflectY):
rotationInDegree = (rotationInDegree - 180)
rotation = (rotation - math.pi)
if(reflectX):
scaleX = (scaleX * -1)
if(reflectY):
scaleY = (scaleY * -1)
return {
'scale':{
'x':scaleX,
'y':scaleY
},
'rotate':{
'degree':rotationInDegree,
'radiance':rotation
},
'reflect':{
'x':str(reflectX),
'y':str(reflectY)
},
'translate':{
'x':tx,
'y':ty
},
'matrix':matrix
}
def matrixToList(self, matrix):
"""
From matrix order,
1 3 5 2 4 6
to sequencial list
1 2 3 4 5 6
"""
return [
matrix[0][0],
matrix[1][0],
matrix[0][1],
matrix[1][1],
matrix[0][2],
matrix[1][2]
]
def movePath(self,node,x,y,origin):
tagName= self.getTagName(node)
if(tagName!= 'path'):
inkex.debug('movePath only works on SVG Path elements. Argument was of type "' + tagName+ '"')
return False
path = simplepath.parsePath(node.get('d'))
id = node.get('id')
box = list(simpletransform.computeBBox([node]))
offset_x = (box[0] - x)
offset_y = (box[2] - (y))
for cmd in path:
params = cmd[1]
i = 0
while(i < len(params)):
if(i % 2 == 0):
#inkex.debug('x point at ' + str( round( params[i] )))
params[i] = (params[i] - offset_x)
#inkex.debug('moved to ' + str( round( params[i] )))
else:
#inkex.debug('y point at ' + str( round( params[i]) ))
params[i] = (params[i] - offset_y)
#inkex.debug('moved to ' + str( round( params[i] )))
i = i + 1
return simplepath.formatPath(path)
def scourDoc(self,str):
return scourString(str).encode("UTF-8")
def saveToFile(self,content,filename):
FILE = open(filename,'w')
if(FILE):
FILE.write(content)
FILE.close()
return True
else:
return False
def viewOutput(self,url):
runner = BrowserRunner()
runner.url = url
runner.start()
class BrowserRunner(threading.Thread):
url = ''
def __init__(self):
threading.Thread.__init__ (self)
def run(self):
webbrowser.open('file://' + self.url)
# Create effect instance and apply it.
effect = ExtractElements()
effect.affect(output=False)
#inkex.errormsg(_("This will be written to Python stderr"))