-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathbuzzard.py
1220 lines (1019 loc) · 57.7 KB
/
buzzard.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from svgpathtools import Line, QuadraticBezier, CubicBezier, Path, Arc, svg2paths2
from svgelements import Path as elPath, Matrix
from freetype import Face #pip install freetype-py
from modules.svgstring2path import string2paths
import numpy as np
import argparse
import svgwrite
import bezier #pip install bezier
import math
import subprocess
import os
import sys
import re
import xml.etree.ElementTree as XMLET
import shlex
import time
import json
# Fix dirpath errors in frozen EXE release
if getattr(sys, 'frozen', False):
# If the application is run as a bundle, the PyInstaller bootloader
# extends the sys module by a flag frozen=True and sets the app
# path into variable _MEIPASS'.
# FOR ONE-FOLDER BUNDLES:
# application_path = sys._MEIPASS
# FOR ONE-FILE BUNDLES:
application_path = os.path.dirname(sys.executable)
else:
application_path = os.path.dirname(os.path.abspath(__file__))
# Takes an x/y tuple and returns a complex number
def tuple_to_imag(t):
return t[0] + t[1] * 1j
# The freetype library doesn't reliably report the
# bounding box size of a glyph, so instead we figure
# it out and store it here
class boundingBox:
def __init__(self, xMax, yMax, xMin, yMin):
self.xMax = xMax
self.yMax = yMax
self.xMin = xMin
self.yMin = yMin
# Global variables (most of these are rewritten by CLI args later)
SCALE = 1 / 90
SUBSAMPLING = 1
SIMPLIFY = 0.1 * SCALE
SIMPLIFYHQ = False
TRACEWIDTH = '0.1'
# ******************************************************************************
#
# Create SVG Document containing properly formatted inString
#
#
def renderLabel(inString):
dwg = svgwrite.Drawing() # SVG drawing in memory
strIdx = 0 # Used to iterate over inString
xOffset = 100 # Cumulative character placement offset
yOffset = 0 # Cumulative character placement offset
charSizeX = 8 # Character size constant
charSizeY = 8 # Character size constant
baseline = 170 # Y value of text baseline
leftCap = '' # Used to store cap shape for left side of tag
rightCap = '' # Used to store cap shape for right side of tag
removeTag = False # Track whether characters need to be removed from string ends
glyphBounds = [] # List of boundingBox objects to track rendered character size
finalSegments = [] # List of output paths
escaped = False # Track whether the current character was preceded by a '\'
lineover = False # Track whether the current character needs to be lined over
lineoverList = []
# If we can't find the typeface that the user requested, we have to quit
try:
if args.verbose:
print("Looking for typeface in " + application_path + '\\typeface\\')
face = Face(application_path + '\\typeface\\' + args.fontName + '.ttf')
face.set_char_size(charSizeX,charSizeY,200,200)
except:
print("WARN: No Typeface found with the name " + args.fontName + ".ttf")
sys.exit(0) # quit Python
# If the typeface that the user requested exists, but there's no position table for it, we'll continue with a warning
try:
f = open(application_path + '\\typeface\\' + args.fontName + ".json")
table = json.load(f)
f.close()
glyphPos = table["glyphPos"]
spaceDistance = table["spaceDistance"]
for key in glyphPos:
glyphPos[key] = complex(glyphPos[key])
except:
glyphPos = 0
spaceDistance = 60
print("WARN: No Position Table found for this typeface. Composition will be haphazard at best.")
pass
# If there's lineover text, drop the text down to make room for the line
dropBaseline = False
a = False
b = False
x = 0
while x < len(inString):
if x > 0 and inString[x] == '\\':
a = True
if x != len(inString)-1:
x += 1
if inString[x] == '!' and not a:
dropBaseline = True
a = False
x += 1
if dropBaseline:
baseline = 190
# Detect and Remove tag style indicators
if inString[0] == '(':
leftCap = 'round'
removeTag = True
elif inString[0] == '[':
leftCap = 'square'
removeTag = True
elif inString[0] == '<':
leftCap = 'pointer'
removeTag = True
elif inString[0] == '>':
leftCap = 'flagtail'
removeTag = True
elif inString[0] == '/':
leftCap = 'fslash'
removeTag = True
elif inString[0] == '\\':
leftCap = 'bslash'
removeTag = True
if removeTag:
inString = inString[1:]
removeTag = False
if inString[-1] == ')':
rightCap = 'round'
removeTag = True
elif inString[-1] == ']':
rightCap = 'square'
removeTag = True
elif inString[-1] == '>':
rightCap = 'pointer'
removeTag = True
elif inString[-1] == '<':
rightCap = 'flagtail'
removeTag = True
elif inString[-1] == '/':
rightCap = 'fslash'
removeTag = True
elif inString[-1] == '\\':
rightCap = 'bslash'
removeTag = True
if removeTag:
inString = inString[:len(inString)-1]
# Draw and compose the glyph portion of the tag
# The way that this loop works was confusing when revisiting to fix a bug
# Additional notes have been added (7/22)
for charIdx in range(len(inString)):
# If this is a non-escaped '!' mark the beginning of lineover
# Define this glyph as having no size and fire the "linover" flag
# This flag is used when a renderable character gets handled to
# mark the beginning and end of the lineover
if inString[charIdx] == '!' and not escaped:
glyphBounds.append(boundingBox(0,0,0,0))
lineover = True
# If we've hit the end of the string but not the end of the lineover
# then the loop will escape here before being able to draw the lineover
# so we need to finish the lineover before escaping
if charIdx == len(inString)-1 and len(lineoverList) > 0:
linePaths = []
linePaths.append(Line(start=complex(lineoverList[0], 10), end=complex(xOffset,10)))
linePaths.append(Line(start=complex(xOffset,10), end=complex(xOffset,30)))
linePaths.append(Line(start=complex(xOffset,30), end=complex(lineoverList[0], 30)))
linePaths.append(Line(start=complex(lineoverList[0], 30), end=complex(lineoverList[0], 10)))
linepath = Path(*linePaths)
linepath = elPath(linepath.d())
finalSegments.append(linepath)
lineover = False
lineoverList.clear()
continue
# Check whether this character is a backslash that isn't escaped
# and isn't the first character (denoting a backslash-shaped tag)
if inString[charIdx] == '\\' and charIdx > 0 and not escaped:
glyphBounds.append(boundingBox(0,0,0,0))
escaped = True
continue
# Check whether this character is a space
if inString[charIdx] == ' ':
# If we've hit the end of the string but not the end of the lineover
# then the loop will escape here before being able to draw the lineover
# so we need to finish the lineover before escaping
if charIdx == len(inString)-1 and len(lineoverList) > 0:
linePaths = []
linePaths.append(Line(start=complex(lineoverList[0], 10), end=complex(xOffset,10)))
linePaths.append(Line(start=complex(xOffset,10), end=complex(xOffset,30)))
linePaths.append(Line(start=complex(xOffset,30), end=complex(lineoverList[0], 30)))
linePaths.append(Line(start=complex(lineoverList[0], 30), end=complex(lineoverList[0], 10)))
linepath = Path(*linePaths)
linepath = elPath(linepath.d())
finalSegments.append(linepath)
lineover = False
lineoverList.clear()
# Define this glyph as having no size and add the space-width to the xOffset
glyphBounds.append(boundingBox(0,0,0,0))
xOffset += spaceDistance
continue
# All special cases end in 'continue' so if we've gotten here we can clear our flags
if escaped:
escaped = False
face.load_char(inString[charIdx]) # Load character curves from font
outline = face.glyph.outline # Save character curves to var
y = [t[1] for t in outline.points]
# flip the points
outline_points = [(p[0], max(y) - p[1]) for p in outline.points]
start, end = 0, 0
paths = []
box = 0
yOffset = 0
for i in range(len(outline.contours)):
end = outline.contours[i]
points = outline_points[start:end + 1]
points.append(points[0])
tags = outline.tags[start:end + 1]
tags.append(tags[0])
segments = [[points[0], ], ]
box = boundingBox(points[0][0],points[0][1],points[0][0],points[0][1])
for j in range(1, len(points)):
if not tags[j]: # if this point is off-path
if tags[j-1]: # and the last point was on-path
segments[-1].append(points[j]) # toss this point onto the segment
elif not tags[j-1]: # and the last point was off-path
# get center point of two
newPoint = ((points[j][0] + points[j-1][0]) / 2.0,
(points[j][1] + points[j-1][1]) / 2.0)
segments[-1].append(newPoint) # toss this new point onto the segment
segments.append([newPoint, points[j], ]) # and start a new segment with the new point and this one
elif tags[j]: # if this point is on-path
segments[-1].append(points[j]) # toss this point onto the segment
if j < (len(points) - 1):
segments.append([points[j], ]) # and start a new segment with this point if we're not at the end
for segment in segments:
if len(segment) == 2:
paths.append(Line(start=tuple_to_imag(segment[0]),
end=tuple_to_imag(segment[1])))
elif len(segment) == 3:
paths.append(QuadraticBezier(start=tuple_to_imag(segment[0]),
control=tuple_to_imag(segment[1]),
end=tuple_to_imag(segment[2])))
start = end + 1
# Derive bounding box of character
for segment in paths:
i = 0
while i < 10:
point = segment.point(0.1*i)
if point.real > box.xMax:
box.xMax = point.real
if point.imag > box.yMax:
box.yMax = point.imag
if point.real < box.xMin:
box.xMin = point.real
if point.imag < box.yMin:
box.yMin = point.imag
i += 1
glyphBounds.append(box)
path = Path(*paths)
if glyphPos != 0:
try:
xOffset += glyphPos[inString[charIdx]].real
yOffset = glyphPos[inString[charIdx]].imag
except:
pass
# If we've reached this point and the lineover flag is set, that means that we need
# to either store the beginning offset of the lineover, or render the lineover.
# We use a list object called "lineoverList" to store the offset for the beginning
# of a lineover. We can use this list object to determine which action needs to be taken.
# If we have no stored offset in lineoverList, then this is the beginning of a lineover
# and we store the offset before resetting the flag...
if lineover and len(lineoverList) == 0:
lineoverList.append(xOffset)
lineover = False
# ...If there is an offset in lineoverList, then we need to finish the lineover,
# reset the flag, and clear the lineoverList
if (lineover and len(lineoverList) > 0):
linePaths = []
linePaths.append(Line(start=complex(lineoverList[0], 10), end=complex(xOffset,10)))
linePaths.append(Line(start=complex(xOffset,10), end=complex(xOffset,30)))
linePaths.append(Line(start=complex(xOffset,30), end=complex(lineoverList[0], 30)))
linePaths.append(Line(start=complex(lineoverList[0], 30), end=complex(lineoverList[0], 10)))
linepath = Path(*linePaths)
linepath = elPath(linepath.d())
finalSegments.append(linepath)
lineover = False
lineoverList.clear()
pathTransform = Matrix.translate(xOffset, baseline+yOffset-box.yMax)
path = elPath(path.d()) * pathTransform
path = elPath(path.d())
finalSegments.append(path)
xOffset += 30
if glyphPos != 0:
try:
xOffset -= glyphPos[inString[charIdx]].real
except:
pass
xOffset += (glyphBounds[charIdx].xMax - glyphBounds[charIdx].xMin)
# This is where we handle the "implicit" case, a tag that ends before the lineover
# is explicitly closed (no ending '!') We do this at the very end of the loop so that
# the final character's offsets are calculated and the lineover reaches the end of the tag
if charIdx == len(inString)-1 and len(lineoverList) > 0:
linePaths = []
linePaths.append(Line(start=complex(lineoverList[0], 10), end=complex(xOffset,10)))
linePaths.append(Line(start=complex(xOffset,10), end=complex(xOffset,30)))
linePaths.append(Line(start=complex(xOffset,30), end=complex(lineoverList[0], 30)))
linePaths.append(Line(start=complex(lineoverList[0], 30), end=complex(lineoverList[0], 10)))
linepath = Path(*linePaths)
linepath = elPath(linepath.d())
finalSegments.append(linepath)
lineover = False
lineoverList.clear()
strIdx += 1
if leftCap == '' and rightCap == '':
for i in range(len(finalSegments)):
svgObj = dwg.add(dwg.path(finalSegments[i].d()))
svgObj['fill'] = "#000000"
else:
#draw the outline of the label as a filled shape and
#subtract each latter from it
tagPaths = []
if rightCap == 'round':
tagPaths.append(Line(start=complex(100,0), end=complex(xOffset,0)))
tagPaths.append(Arc(start=complex(xOffset,0), radius=complex(100,100), rotation=180, large_arc=1, sweep=1, end=complex(xOffset,200)))
elif rightCap == 'square':
tagPaths.append(Line(start=complex(100,0), end=complex(xOffset,0)))
tagPaths.append(Line(start=complex(xOffset,0), end=complex(xOffset+50,0)))
tagPaths.append(Line(start=complex(xOffset+50,0), end=complex(xOffset+50,200)))
tagPaths.append(Line(start=complex(xOffset+50,200), end=complex(xOffset,200)))
elif rightCap == 'pointer':
tagPaths.append(Line(start=complex(100,0), end=complex(xOffset,0)))
tagPaths.append(Line(start=complex(xOffset,0), end=complex(xOffset+50,0)))
tagPaths.append(Line(start=complex(xOffset+50,0), end=complex(xOffset+100,100)))
tagPaths.append(Line(start=complex(xOffset+100,100), end=complex(xOffset+50,200)))
tagPaths.append(Line(start=complex(xOffset+50,200), end=complex(xOffset,200)))
elif rightCap == 'flagtail':
tagPaths.append(Line(start=complex(100,0), end=complex(xOffset,0)))
tagPaths.append(Line(start=complex(xOffset,0), end=complex(xOffset+100,0)))
tagPaths.append(Line(start=complex(xOffset+100,0), end=complex(xOffset+50,100)))
tagPaths.append(Line(start=complex(xOffset+50,100), end=complex(xOffset+100,200)))
tagPaths.append(Line(start=complex(xOffset+100,200), end=complex(xOffset,200)))
elif rightCap == 'fslash':
tagPaths.append(Line(start=complex(100,0), end=complex(xOffset,0)))
tagPaths.append(Line(start=complex(xOffset,0), end=complex(xOffset+50,0)))
tagPaths.append(Line(start=complex(xOffset+50,0), end=complex(xOffset,200)))
elif rightCap == 'bslash':
tagPaths.append(Line(start=complex(100,0), end=complex(xOffset,0)))
tagPaths.append(Line(start=complex(xOffset,0), end=complex(xOffset+50,200)))
tagPaths.append(Line(start=complex(xOffset+50,200), end=complex(xOffset,200)))
elif rightCap == '' and leftCap != '':
tagPaths.append(Line(start=complex(100,0), end=complex(xOffset,0)))
tagPaths.append(Line(start=complex(xOffset,0), end=complex(xOffset,200)))
if leftCap == 'round':
tagPaths.append(Line(start=complex(xOffset,200), end=complex(100,200)))
tagPaths.append(Arc(start=complex(100,200), radius=complex(100,100), rotation=180, large_arc=0, sweep=1, end=complex(100,0)))
elif leftCap == 'square':
tagPaths.append(Line(start=complex(xOffset,200), end=complex(100,200)))
tagPaths.append(Line(start=complex(100,200), end=complex(50,200)))
tagPaths.append(Line(start=complex(50,200), end=complex(50,0)))
tagPaths.append(Line(start=complex(50,0), end=complex(100,0)))
elif leftCap == 'pointer':
tagPaths.append(Line(start=complex(xOffset,200), end=complex(100,200)))
tagPaths.append(Line(start=complex(100,200), end=complex(50,200)))
tagPaths.append(Line(start=complex(50,200), end=complex(0,100)))
tagPaths.append(Line(start=complex(0,100), end=complex(50,0)))
tagPaths.append(Line(start=complex(50,0), end=complex(100,0)))
elif leftCap == 'flagtail':
tagPaths.append(Line(start=complex(xOffset,200), end=complex(100,200)))
tagPaths.append(Line(start=complex(100,200), end=complex(0,200)))
tagPaths.append(Line(start=complex(0,200), end=complex(50,100)))
tagPaths.append(Line(start=complex(50,100), end=complex(0,0)))
tagPaths.append(Line(start=complex(0,0), end=complex(100,0)))
elif leftCap == 'fslash':
tagPaths.append(Line(start=complex(xOffset,200), end=complex(100,200)))
tagPaths.append(Line(start=complex(100,200), end=complex(50,200)))
tagPaths.append(Line(start=complex(50,200), end=complex(100,0)))
elif leftCap == 'bslash':
tagPaths.append(Line(start=complex(xOffset,200), end=complex(100,200)))
tagPaths.append(Line(start=complex(100,200), end=complex(50,0)))
tagPaths.append(Line(start=complex(50,0), end=complex(100,0)))
elif leftCap == '' and rightCap != '':
tagPaths.append(Line(start=complex(xOffset,200), end=complex(100,200)))
tagPaths.append(Line(start=complex(100,200), end=complex(100,0)))
path = Path(*tagPaths)
for i in range(len(finalSegments)):
path = elPath(path.d()+" "+finalSegments[i].reverse())
tagObj = dwg.add(dwg.path(path.d()))
tagObj['fill'] = "#000000"
dwg['width'] = xOffset+100
dwg['height'] = 250
#dwg.saveas('out.svg')
return dwg
# Use Pythagoras to find the distance between two points
def dist(a, b):
dx = a.real - b.real
dy = a.imag - b.imag
return math.sqrt(dx * dx + dy * dy)
# Parse a style tag into a dictionary
def styleParse(attr):
out = dict()
i = 0
for tag in attr.split(';'):
out[tag.split(':')[0]] = tag.split(':')[1]
i += 1
return out
# ray-casting algorithm based on
# http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
def isInside(point, poly):
x = point.real
y = point.imag
inside = False
i = 0
j = len(poly) - 1
while i < len(poly):
xi = poly[i].real
yi = poly[i].imag
xj = poly[j].real
yj = poly[j].imag
intersect = ((yi > y) != (yj > y)) and (x < ((xj - xi) * (y - yi) / (yj - yi) + xi))
if intersect:
inside = not inside
j = i
i += 1
return inside
# Shoelace Formula without absolute value which returns negative if points are CCW
# https://stackoverflow.com/questions/14505565/detect-if-a-set-of-points-in-an-array-that-are-the-vertices-of-a-complex-polygon
def polygonArea(poly):
area = 0
i = 0
while i < len(poly):
j = (i + 1) % len(poly)
area += poly[i].real * poly[j].imag
area -= poly[j].real * poly[i].imag
i += 1
return area / 2
# Move a small distance away from path[idxa] towards path[idxb]
def interpPt(path, idxa, idxb):
# a fraction of the trace width so we don't get much of a notch in the line
amt = float(TRACEWIDTH) / 8
# wrap index
if idxb < 0:
idxb += len(path)
if idxb >= len(path):
idxb -= len(path)
# get 2 pts
a = path[idxa]
b = path[idxb]
dx = b.real - a.real
dy = b.imag - a.imag
d = math.sqrt(dx * dx + dy * dy)
if amt > d:
return # return nothing - will just end up using the last point
return complex(a.real + (dx * amt / d), a.imag + (dy * amt / d))
# Some svg paths conatin multiple nested polygons. We need to open them and splice them together.
def unpackPoly(poly):
# ensure all polys are the right way around
if args.verbose:
print('...Unpacking ' + str(len(poly)) + ' Polygons')
p = 0
while p < len(poly):
if polygonArea(poly[p]) > 0:
poly[p].reverse()
if args.verbose:
print('...Polygon #'+str(p)+' was backwards, reversed')
p += 1
# check for polys that are within more than 1 other poly,
# extract them now, then we append them later
# This isn't a perfect solution and only handles a single nesting
extraPolys = []
polyTmp = []
for j in range(len(poly)):
c = 0
for k in range(len(poly)):
if j == k:
continue
if isInside(poly[j][0], poly[k]):
c += 1
if c > 1:
extraPolys.append(poly[j])
else:
polyTmp.append(poly[j])
poly = polyTmp
finalPolys = [poly[0]]
p = 1
while p < len(poly):
path = poly[p]
outerPolyIndex = 'undefined'
i = 0
while i < len(finalPolys):
if isInside(path[0], finalPolys[i]):
outerPolyIndex = i
break
elif isInside(finalPolys[i][0], path):
# polys in wrong order - old one is inside new one
t = path
path = finalPolys[i]
finalPolys[i] = t
outerPolyIndex = i
break
i += 1
if outerPolyIndex != 'undefined':
path.reverse() # reverse poly
outerPoly = finalPolys[outerPolyIndex]
minDist = 10000000000
minOuter = 0
minPath = 0
a = 0
while a < len(outerPoly):
b = 0
while b < len(path):
l = dist(outerPoly[a], path[b])
if l < minDist:
minDist = l
minOuter = a
minPath = b
b += 1
a += 1
# splice the inner poly into the outer poly
# but we have to recess the two joins a little
# otherwise Eagle reports Invalid poly when filling
# the top layer
finalPolys[outerPolyIndex] = outerPoly[0:minOuter]
stub = interpPt(outerPoly, minOuter, minOuter - 1)
(finalPolys[outerPolyIndex].append(stub) if stub is not None else None)
stub = interpPt(path, minPath, minPath + 1)
(finalPolys[outerPolyIndex].append(stub) if stub is not None else None)
finalPolys[outerPolyIndex].extend(path[minPath + 1:])
finalPolys[outerPolyIndex].extend(path[:minPath])
stub = interpPt(path, minPath, minPath - 1)
(finalPolys[outerPolyIndex].append(stub) if stub is not None else None)
stub = interpPt(outerPoly, minOuter, minOuter + 1)
(finalPolys[outerPolyIndex].append(stub) if stub is not None else None)
finalPolys[outerPolyIndex].extend(outerPoly[minOuter + 1:])
else:
# not inside, just add this poly
finalPolys.append(path)
p += 1
#print(finalPolys)
return finalPolys + extraPolys
#
#
# ******************************************************************************
#
# Convert SVG paths to various EAGLE polygon formats
#
#
def drawSVG(svg_attributes, attributes, paths):
global SCALE
global SUBSAMPLING
global SIMPLIFY
global SIMPLIFYHQ
global TRACEWIDTH
out = ''
svgWidth = 0
svgHeight = 0
if 'viewBox' in svg_attributes.keys():
if svg_attributes['viewBox'].split()[2] != '0':
svgWidth = str(
round(float(svg_attributes['viewBox'].split()[2]), 2))
svgHeight = str(
round(float(svg_attributes['viewBox'].split()[3]), 2))
else:
svgWidth = svg_attributes['width']
svgHeight = svg_attributes['height']
else:
svgWidth = svg_attributes['width']
svgHeight = svg_attributes['height']
specifiedWidth = svg_attributes['width']
if 'mm' in specifiedWidth:
specifiedWidth = float(specifiedWidth.replace('mm', ''))
SCALE = specifiedWidth / float(svgWidth)
if args.verbose:
print("SVG width detected in mm \\o/")
elif 'in' in specifiedWidth:
specifiedWidth = float(specifiedWidth.replace('in', '')) * 25.4
SCALE = specifiedWidth / float(svgWidth)
if args.verbose:
print("SVG width detected in inches")
else:
SCALE = (args.scaleFactor * 25.4) / 150
if args.verbose:
print("SVG width not found, guessing based on scale factor")
exportHeight = float(svgHeight) * SCALE
if args.outMode == "b":
out += "CHANGE layer " + str(args.eagleLayerNumber) + \
"; CHANGE rank 3; CHANGE pour solid; SET WIRE_BEND 2;\n"
if args.outMode == "ls":
out += "CHANGE layer " + str(args.eagleLayerNumber) + \
"; CHANGE pour solid; Grid mm; SET WIRE_BEND 2;\n"
if args.outMode == "ki":
out += "(footprint \"buzzardLabel\"\n" + \
" (layer \"F.Cu\")\n" + \
" (attr board_only exclude_from_pos_files exclude_from_bom)\n"
if args.outMode == "ki5":
out += "(module \"buzzardLabel\"" + \
" (layer \"F.Cu\")" + \
" (tedit \"" + hex(int(time.time()))[2:-1].upper() + "\")\n" + \
" (attr virtual)\n"
if len(paths) == 0:
print("No paths found. Did you use 'Object to path' in Inkscape?")
anyVisiblePaths = False
i = 0
while i < len(paths):
if args.verbose:
print('Translating Path ' + str(i+1) + ' of ' + str(len(paths)))
# Apply the tranform from this svg object to actually transform the points
# We need the Matrix object from svgelements but we can only matrix multiply with
# svgelements' version of the Path object so we're gonna do some dumb stuff
# to launder the Path object from svgpathtools through a d-string into
# svgelements' version of Path. Luckily, the Path object from svgelements has
# backwards compatible .point methods
pathTransform = Matrix('')
if 'transform' in attributes[i].keys():
pathTransform = Matrix(attributes[i]['transform'])
if args.verbose:
print('...Applying Transforms')
path = elPath(paths[i].d()) * pathTransform
path = elPath(path.d())
# Another stage of transforms that gets applied to all paths
# in order to shift the label around the origin
tx = {
'l':0,
'c':0-(float(svgWidth)/2),
'r':0-float(svgWidth)
}
ty = {
't':250,
'c':150,
'b':50
}
path = elPath(paths[i].d()) * Matrix.translate(tx[args.originPos[1]],ty[args.originPos[0]])
path = elPath(path.d())
style = 0
if 'style' in attributes[i].keys():
style = styleParse(attributes[i]['style'])
if 'fill' in attributes[i].keys():
filled = attributes[i]['fill'] != 'none' and attributes[i]['fill'] != ''
elif 'style' in attributes[i].keys():
filled = style['fill'] != 'none' and style['fill'] != ''
else:
filled = False
if 'stroke' in attributes[i].keys():
stroked = attributes[i]['stroke'] != 'none' and attributes[i]['stroke'] != ''
elif 'style' in attributes[i].keys():
stroked = style['stroke'] != 'none' and style['stroke'] != ''
else:
stroked = False
if not filled and not stroked:
i += 1
continue # not drawable (clip path?)
SUBSAMPLING = args.subSampling
TRACEWIDTH = str(args.traceWidth)
anyVisiblePaths = True
l = path.length()
divs = round(l * SUBSAMPLING)
if divs < 3:
divs = 3
maxLen = l * 2 * SCALE / divs
p = path.point(0)
p = complex(p.real * SCALE, p.imag * SCALE)
last = p
polys = []
points = []
s = 0
while s <= divs:
p = path.point(s * 1 / divs)
p = complex(p.real * SCALE, p.imag * SCALE)
if dist(p, last) > maxLen:
if len(points) > 1:
points = simplify(points, SIMPLIFY, SIMPLIFYHQ)
polys.append(points)
points = [p]
else:
points.append(p)
last = p
s += 1
if len(points) > 1:
points = simplify(points, SIMPLIFY, SIMPLIFYHQ)
polys.append(points)
if filled:
polys = unpackPoly(polys)
for points in polys:
if len(points) < 2:
return
scriptLine = ''
if filled:
points.append(points[0]) # re-add final point so we loop around
if args.outMode != "lib":
if args.outMode == "b":
scriptLine += "polygon " + args.signalName + " " + TRACEWIDTH + "mm "
if args.outMode == "ls":
scriptLine += "polygon " + TRACEWIDTH + "mm "
if args.outMode.find("ki") == -1:
for p in points:
precisionX = '{0:.2f}'.format(round(p.real, 6))
precisionY = '{0:.2f}'.format(round(exportHeight - p.imag, 6))
scriptLine += '(' + precisionX + 'mm ' + precisionY + 'mm) '
scriptLine += ';'
elif args.outMode.find("ki") != -1:
scriptLine += " (fp_poly (pts"
for p in points:
precisionX = "{0:.2f}".format(round(p.real, 6))
precisionY = "{0:.2f}".format(round(p.imag - exportHeight, 6))
scriptLine += " (xy " + precisionX + " " + precisionY + ")"
if args.outMode == "ki":
scriptLine += ") (layer \"F.SilkS\") (width 0.01) (fill solid))\n"
elif args.outMode == "ki5":
scriptLine += ") (layer \"F.SilkS\") (width 0.01))\n"
else:
scriptLine += "<polygon width=\"" + TRACEWIDTH + "\" layer=\"" + str(args.eagleLayerNumber) + "\">\n"
for p in points:
precisionX = '{0:.2f}'.format(round(p.real, 6))
precisionY = '{0:.2f}'.format(round(exportHeight - p.imag, 6))
scriptLine += "<vertex x=\"" + precisionX + "\" y=\"" + precisionY + "\"/>\n"
scriptLine += "</polygon>"
out += scriptLine + '\n'
i += 1
if not anyVisiblePaths:
print("No paths with fills or strokes found.")
if args.outMode.find("ki") != -1:
out += ')\n'
return out
def generate(labelString):
path_to_script = application_path
if args.stdout:
paths, attributes, svg_attributes = string2paths(renderLabel(labelString).tostring())
try:
print(drawSVG(svg_attributes, attributes, paths))
except:
print("Failed to output")
sys.exit(0) # quit Python
elif args.outMode != 'lib':
paths, attributes, svg_attributes = string2paths(renderLabel(labelString).tostring())
ext = '.scr' if args.outMode.find("ki") == -1 else ".kicad_mod"
try:
f = open(path_to_script + "/" + args.destination + ext, 'w')
f.write(drawSVG(svg_attributes, attributes, paths))
f.close
except:
print("Failed to create output file")
sys.exit(0) # quit Python
else:
labelStrings = labelString.split(",")
scripts = []
for string in labelStrings:
paths, attributes, svg_attributes = string2paths(renderLabel(string).tostring())
scripts.append(drawSVG(svg_attributes, attributes, paths))
try:
output_path = path_to_script + "/" + args.destination + ".lbr"
if args.writeMode == 'a':
new_contents = appendLib(scripts, labelStrings, output_path)
with open(output_path, 'w') as f:
f.write(new_contents)
else:
f = open(output_path, 'w')
f.write(writeLib(scripts, labelStrings))
f.close
except:
print("Failed to create output file")
sys.exit(0) # quit Python
def writeLib(scriptStrings, labelStrings):
head = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE eagle SYSTEM \"eagle.dtd\">\n<eagle version=\"7.7.0\">\n<drawing>\n<settings>\n<setting alwaysvectorfont=\"no\"/>\n<setting verticaltext=\"up\"/>\n</settings>\n<grid distance=\"1\" unitdist=\"mm\" unit=\"mm\" style=\"lines\" multiple=\"1\" display=\"yes\" altdistance=\"0.1\" altunitdist=\"mm\" altunit=\"mm\"/>\n<layers>\n<layer number=\"1\" name=\"Top\" color=\"4\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"2\" name=\"Route2\" color=\"1\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"3\" name=\"Route3\" color=\"4\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"4\" name=\"Route4\" color=\"1\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"5\" name=\"Route5\" color=\"4\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"6\" name=\"Route6\" color=\"1\" fill=\"8\" visible=\"no\" active=\"yes\"/>\n<layer number=\"7\" name=\"Route7\" color=\"4\" fill=\"8\" visible=\"no\" active=\"yes\"/>\n<layer number=\"8\" name=\"Route8\" color=\"1\" fill=\"2\" visible=\"no\" active=\"yes\"/>\n<layer number=\"9\" name=\"Route9\" color=\"4\" fill=\"2\" visible=\"no\" active=\"yes\"/>\n<layer number=\"10\" name=\"Route10\" color=\"1\" fill=\"7\" visible=\"no\" active=\"yes\"/>\n<layer number=\"11\" name=\"Route11\" color=\"4\" fill=\"7\" visible=\"no\" active=\"yes\"/>\n<layer number=\"12\" name=\"Route12\" color=\"1\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"13\" name=\"Route13\" color=\"4\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"14\" name=\"Route14\" color=\"1\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"15\" name=\"Route15\" color=\"4\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"16\" name=\"Bottom\" color=\"1\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"17\" name=\"Pads\" color=\"2\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"18\" name=\"Vias\" color=\"2\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"19\" name=\"Unrouted\" color=\"6\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"20\" name=\"Dimension\" color=\"15\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"21\" name=\"tPlace\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"22\" name=\"bPlace\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"23\" name=\"tOrigins\" color=\"15\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"24\" name=\"bOrigins\" color=\"15\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"25\" name=\"tNames\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"26\" name=\"bNames\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"27\" name=\"tValues\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"28\" name=\"bValues\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"29\" name=\"tStop\" color=\"7\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"30\" name=\"bStop\" color=\"7\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"31\" name=\"tCream\" color=\"7\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"32\" name=\"bCream\" color=\"7\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"33\" name=\"tFinish\" color=\"6\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"34\" name=\"bFinish\" color=\"6\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"35\" name=\"tGlue\" color=\"7\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"36\" name=\"bGlue\" color=\"7\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"37\" name=\"tTest\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"38\" name=\"bTest\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"39\" name=\"tKeepout\" color=\"4\" fill=\"11\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"40\" name=\"bKeepout\" color=\"1\" fill=\"11\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"41\" name=\"tRestrict\" color=\"4\" fill=\"10\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"42\" name=\"bRestrict\" color=\"1\" fill=\"10\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"43\" name=\"vRestrict\" color=\"2\" fill=\"10\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"44\" name=\"Drills\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"45\" name=\"Holes\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"46\" name=\"Milling\" color=\"3\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"47\" name=\"Measures\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"48\" name=\"Document\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"49\" name=\"Reference\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"51\" name=\"tDocu\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"52\" name=\"bDocu\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"90\" name=\"Modules\" color=\"5\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"91\" name=\"Nets\" color=\"2\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"92\" name=\"Busses\" color=\"1\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"93\" name=\"Pins\" color=\"2\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"94\" name=\"Symbols\" color=\"4\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"95\" name=\"Names\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"96\" name=\"Values\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"97\" name=\"Info\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"98\" name=\"Guide\" color=\"6\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n</layers>\n"
tail = "</drawing>\n</eagle>\n"
lbrFile = head + "<library>\n<packages>\n"
serialNum = 0
# Write Packages
for i in range(len(scriptStrings)):
lbrFile += "<package name=\"" + cleanName(labelStrings[i].upper()) + str(serialNum) + "\">\n"
lbrFile += scriptStrings[i]
lbrFile += "</package>\n"
serialNum += 1
lbrFile += "</packages>\n<symbols>\n"
serialNum = 0
# Write Symbols
for i in range(len(scriptStrings)):
lbrFile += "<symbol name=\"" + cleanName(labelStrings[i].upper()) + str(serialNum) + "\">\n"
lbrFile += "<text x=\"0\" y=\"0\" size=\"1.778\" layer=\"94\">" + cleanName(labelStrings[i]) + "</text>\n</symbol>\n"
serialNum += 1
lbrFile += "</symbols>\n<devicesets>\n"
serialNum = 0
# Write Devicesets
for i in range(len(scriptStrings)):
lbrFile += "<deviceset name=\"" + cleanName(labelStrings[i].upper()) + str(serialNum) + "\">\n"
lbrFile += "<gates>\n<gate name=\"G$1\" symbol=\"" + cleanName(labelStrings[i].upper()) + str(serialNum) + "\" x=\"0\" y=\"0\"/>\n</gates>\n<devices>\n"
lbrFile += "<device name=\"\" package=\"" + cleanName(labelStrings[i].upper()) + str(serialNum) + "\">\n<technologies>\n<technology name=\"\"/>\n</technologies>\n</device>\n</devices>\n</deviceset>\n"
serialNum += 1
lbrFile += "</devicesets>\n</library>\n"
lbrFile += tail
return lbrFile
def appendLib(scriptStrings, labelStrings, file):
template = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE eagle SYSTEM \"eagle.dtd\">\n<eagle version=\"7.7.0\">\n<drawing>\n<settings>\n<setting alwaysvectorfont=\"no\"/>\n<setting verticaltext=\"up\"/>\n</settings>\n<grid distance=\"1\" unitdist=\"mm\" unit=\"mm\" style=\"lines\" multiple=\"1\" display=\"yes\" altdistance=\"0.1\" altunitdist=\"mm\" altunit=\"mm\"/>\n<layers>\n<layer number=\"1\" name=\"Top\" color=\"4\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"2\" name=\"Route2\" color=\"1\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"3\" name=\"Route3\" color=\"4\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"4\" name=\"Route4\" color=\"1\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"5\" name=\"Route5\" color=\"4\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"6\" name=\"Route6\" color=\"1\" fill=\"8\" visible=\"no\" active=\"yes\"/>\n<layer number=\"7\" name=\"Route7\" color=\"4\" fill=\"8\" visible=\"no\" active=\"yes\"/>\n<layer number=\"8\" name=\"Route8\" color=\"1\" fill=\"2\" visible=\"no\" active=\"yes\"/>\n<layer number=\"9\" name=\"Route9\" color=\"4\" fill=\"2\" visible=\"no\" active=\"yes\"/>\n<layer number=\"10\" name=\"Route10\" color=\"1\" fill=\"7\" visible=\"no\" active=\"yes\"/>\n<layer number=\"11\" name=\"Route11\" color=\"4\" fill=\"7\" visible=\"no\" active=\"yes\"/>\n<layer number=\"12\" name=\"Route12\" color=\"1\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"13\" name=\"Route13\" color=\"4\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"14\" name=\"Route14\" color=\"1\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"15\" name=\"Route15\" color=\"4\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"16\" name=\"Bottom\" color=\"1\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"17\" name=\"Pads\" color=\"2\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"18\" name=\"Vias\" color=\"2\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"19\" name=\"Unrouted\" color=\"6\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"20\" name=\"Dimension\" color=\"15\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"21\" name=\"tPlace\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"22\" name=\"bPlace\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"23\" name=\"tOrigins\" color=\"15\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"24\" name=\"bOrigins\" color=\"15\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"25\" name=\"tNames\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"26\" name=\"bNames\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"27\" name=\"tValues\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"28\" name=\"bValues\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"29\" name=\"tStop\" color=\"7\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"30\" name=\"bStop\" color=\"7\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"31\" name=\"tCream\" color=\"7\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"32\" name=\"bCream\" color=\"7\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"33\" name=\"tFinish\" color=\"6\" fill=\"3\" visible=\"no\" active=\"yes\"/>\n<layer number=\"34\" name=\"bFinish\" color=\"6\" fill=\"6\" visible=\"no\" active=\"yes\"/>\n<layer number=\"35\" name=\"tGlue\" color=\"7\" fill=\"4\" visible=\"no\" active=\"yes\"/>\n<layer number=\"36\" name=\"bGlue\" color=\"7\" fill=\"5\" visible=\"no\" active=\"yes\"/>\n<layer number=\"37\" name=\"tTest\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"38\" name=\"bTest\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"39\" name=\"tKeepout\" color=\"4\" fill=\"11\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"40\" name=\"bKeepout\" color=\"1\" fill=\"11\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"41\" name=\"tRestrict\" color=\"4\" fill=\"10\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"42\" name=\"bRestrict\" color=\"1\" fill=\"10\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"43\" name=\"vRestrict\" color=\"2\" fill=\"10\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"44\" name=\"Drills\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"45\" name=\"Holes\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"46\" name=\"Milling\" color=\"3\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"47\" name=\"Measures\" color=\"7\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"48\" name=\"Document\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"49\" name=\"Reference\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"51\" name=\"tDocu\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"52\" name=\"bDocu\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"90\" name=\"Modules\" color=\"5\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"91\" name=\"Nets\" color=\"2\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"92\" name=\"Busses\" color=\"1\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"93\" name=\"Pins\" color=\"2\" fill=\"1\" visible=\"no\" active=\"yes\"/>\n<layer number=\"94\" name=\"Symbols\" color=\"4\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"95\" name=\"Names\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"96\" name=\"Values\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"97\" name=\"Info\" color=\"7\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n<layer number=\"98\" name=\"Guide\" color=\"6\" fill=\"1\" visible=\"yes\" active=\"yes\"/>\n</layers>\n<library>\n<packages>\n</packages>\n<symbols>\n</symbols>\n<devicesets>\n</devicesets>\n</library>\n</drawing>\n</eagle>\n"
# end_num_re = re.compile('[0-9]*$')
end_num_re = re.compile('(?P<order>[0-9]+)')
#EXPECT ISSUE FOR COMPILE?
if os.path.exists(file):
tree = XMLET.parse(file)
root = tree.getroot()
else:
root = XMLET.fromstring(template)
lastSerialNum = None
# find out what serial number to use at the beginning
symbols = next(root.iter('symbols'))
for symbol in symbols:
matches = end_num_re.search(symbol.attrib["name"])
if matches != None:
num = int(matches.group())
if lastSerialNum == None:
lastSerialNum = num + 1
else:
if num >= lastSerialNum:
lastSerialNum = num + 1
if lastSerialNum == None:
lastSerialNum = 0
serialNum = lastSerialNum
# Write Packages
packages = next(root.iter('packages'))
for i in range(len(scriptStrings)):
element = XMLET.SubElement(packages, 'package')
element.attrib = {"name" : cleanName(labelStrings[i].upper()) + str(serialNum)}
subroot = XMLET.fromstring("<root>" + scriptStrings[i] + "</root>")
for subelement in subroot:
element.append(subelement)
serialNum += 1
serialNum = lastSerialNum
# Write Symbols
symbols = next(root.iter('symbols'))
for i in range(len(scriptStrings)):
element = XMLET.SubElement(symbols, 'symbol')
element.attrib = {"name" : cleanName(labelStrings[i].upper()) + str(serialNum)}
subroot = XMLET.fromstring("<root>" + "<text x=\"0\" y=\"0\" size=\"1.778\" layer=\"94\">" + cleanName(labelStrings[i]) + "</text>" + "</root>")
for subelement in subroot:
element.append(subelement)
serialNum += 1
serialNum = lastSerialNum
# Write Devicesets
devicesets = next(root.iter('devicesets'))
for i in range(len(scriptStrings)):
element = XMLET.SubElement(devicesets, 'deviceset')
element.attrib = {"name" : cleanName(labelStrings[i].upper()) + str(serialNum)}
subroot = XMLET.fromstring("<root>" + "<gates>\n<gate name=\"G$1\" symbol=\"" + cleanName(labelStrings[i].upper()) + str(serialNum) + "\" x=\"0\" y=\"0\"/>\n</gates>\n<devices>\n<device name=\"\" package=\"" + cleanName(labelStrings[i].upper()) + str(serialNum) + "\">\n<technologies>\n<technology name=\"\"/>\n</technologies>\n</device>\n</devices>\n" + "</root>")
for subelement in subroot:
# print(subelement)
element.append(subelement)
serialNum += 1
# make sure there are newlines after every element
# good solution from SO: https://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python/33956544#33956544
def indent(elem, level=0):
indent_string="" # you can choose various symbols / strings to indent with... use "" for no indentation
i = "\n" + level*indent_string
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + indent_string
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
indent(root)
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE eagle SYSTEM \"eagle.dtd\">\n" + XMLET.tostring(root, encoding='unicode', method='xml')